diff --git a/.gitignore b/.gitignore index 966499f4..a48a5529 100644 --- a/.gitignore +++ b/.gitignore @@ -22,4 +22,5 @@ # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml hs_err_pid* *.iml -*.idea/ \ No newline at end of file +*.idea/ +.DS_Store diff --git a/02nio/nio02/src/main/java/io/github/kimmking/gateway/NettyServerApplication.java b/02nio/nio02/src/main/java/io/github/kimmking/gateway/NettyServerApplication.java index 870b2d4f..049be6b6 100644 --- a/02nio/nio02/src/main/java/io/github/kimmking/gateway/NettyServerApplication.java +++ b/02nio/nio02/src/main/java/io/github/kimmking/gateway/NettyServerApplication.java @@ -9,7 +9,7 @@ public class NettyServerApplication { public final static String GATEWAY_VERSION = "1.0.0"; public static void main(String[] args) { - String proxyServer = System.getProperty("proxyServer","http://localhost:8088"); + String proxyServer = System.getProperty("proxyServer","http://localhost:8803"); String proxyPort = System.getProperty("proxyPort","8888"); // http://localhost:8888/api/hello ==> gateway API diff --git a/02nio/nio02/src/main/java/io/github/kimmking/gateway/filter/HeaderFilter.java b/02nio/nio02/src/main/java/io/github/kimmking/gateway/filter/HeaderFilter.java new file mode 100644 index 00000000..8602d8be --- /dev/null +++ b/02nio/nio02/src/main/java/io/github/kimmking/gateway/filter/HeaderFilter.java @@ -0,0 +1,11 @@ +package io.github.kimmking.gateway.filter; + +import io.netty.channel.ChannelHandlerContext; +import io.netty.handler.codec.http.FullHttpRequest; + +public class HeaderFilter implements HttpRequestFilter{ + @Override + public void filter(FullHttpRequest fullRequest, ChannelHandlerContext ctx) { + fullRequest.headers().add("nio","yinan"); + } +} diff --git a/02nio/nio02/src/main/java/io/github/kimmking/gateway/inbound/HttpInboundHandler.java b/02nio/nio02/src/main/java/io/github/kimmking/gateway/inbound/HttpInboundHandler.java index 22fb2525..c2717c62 100644 --- a/02nio/nio02/src/main/java/io/github/kimmking/gateway/inbound/HttpInboundHandler.java +++ b/02nio/nio02/src/main/java/io/github/kimmking/gateway/inbound/HttpInboundHandler.java @@ -1,22 +1,40 @@ package io.github.kimmking.gateway.inbound; +import io.github.kimmking.gateway.filter.HeaderFilter; +import io.github.kimmking.gateway.outbound.httpclient.HttpClientOutboundHandler; import io.github.kimmking.gateway.outbound.httpclient4.HttpOutboundHandler; +import io.github.kimmking.gateway.outbound.netty4.NettyOutboundHandler; +import io.netty.buffer.Unpooled; +import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; +import io.netty.handler.codec.http.DefaultFullHttpResponse; import io.netty.handler.codec.http.FullHttpRequest; +import io.netty.handler.codec.http.FullHttpResponse; +import io.netty.handler.codec.http.HttpUtil; import io.netty.util.ReferenceCountUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import static io.netty.handler.codec.http.HttpHeaderNames.CONNECTION; +import static io.netty.handler.codec.http.HttpHeaderValues.KEEP_ALIVE; +import static io.netty.handler.codec.http.HttpResponseStatus.NO_CONTENT; +import static io.netty.handler.codec.http.HttpResponseStatus.OK; +import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1; + public class HttpInboundHandler extends ChannelInboundHandlerAdapter { private static Logger logger = LoggerFactory.getLogger(HttpInboundHandler.class); private final String proxyServer; private HttpOutboundHandler handler; +// private HttpClientOutboundHandler handler; +// private NettyOutboundHandler handler; public HttpInboundHandler(String proxyServer) { this.proxyServer = proxyServer; handler = new HttpOutboundHandler(this.proxyServer); +// handler = new HttpClientOutboundHandler(this.proxyServer); +// handler = new NettyOutboundHandler(this.proxyServer); } @Override @@ -29,12 +47,12 @@ public void channelRead(ChannelHandlerContext ctx, Object msg) { try { //logger.info("channelRead流量接口请求开始,时间为{}", startTime); FullHttpRequest fullRequest = (FullHttpRequest) msg; -// String uri = fullRequest.uri(); -// //logger.info("接收到的请求url为{}", uri); -// if (uri.contains("/test")) { -// handlerTest(fullRequest, ctx); -// } - + String uri = fullRequest.uri(); + //logger.info("接收到的请求url为{}", uri); + if (uri.contains("/test")) { + handlerTest(fullRequest, ctx); + } + new HeaderFilter().filter(fullRequest, ctx); handler.handle(fullRequest, ctx); } catch(Exception e) { @@ -44,33 +62,33 @@ public void channelRead(ChannelHandlerContext ctx, Object msg) { } } -// private void handlerTest(FullHttpRequest fullRequest, ChannelHandlerContext ctx) { -// FullHttpResponse response = null; -// try { -// String value = "hello,kimmking"; -// response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(value.getBytes("UTF-8"))); -// response.headers().set("Content-Type", "application/json"); -// response.headers().setInt("Content-Length", response.content().readableBytes()); -// -// } catch (Exception e) { -// logger.error("处理测试接口出错", e); -// response = new DefaultFullHttpResponse(HTTP_1_1, NO_CONTENT); -// } finally { -// if (fullRequest != null) { -// if (!HttpUtil.isKeepAlive(fullRequest)) { -// ctx.write(response).addListener(ChannelFutureListener.CLOSE); -// } else { -// response.headers().set(CONNECTION, KEEP_ALIVE); -// ctx.write(response); -// } -// } -// } -// } -// -// @Override -// public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { -// cause.printStackTrace(); -// ctx.close(); -// } + private void handlerTest(FullHttpRequest fullRequest, ChannelHandlerContext ctx) { + FullHttpResponse response = null; + try { + String value = "hello,yinan"; + response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(value.getBytes("UTF-8"))); + response.headers().set("Content-Type", "application/json"); + response.headers().setInt("Content-Length", response.content().readableBytes()); + + } catch (Exception e) { + logger.error("处理测试接口出错", e); + response = new DefaultFullHttpResponse(HTTP_1_1, NO_CONTENT); + } finally { + if (fullRequest != null) { + if (!HttpUtil.isKeepAlive(fullRequest)) { + ctx.write(response).addListener(ChannelFutureListener.CLOSE); + } else { + response.headers().set(CONNECTION, KEEP_ALIVE); + ctx.write(response); + } + } + } + } + + @Override + public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { + cause.printStackTrace(); + ctx.close(); + } } diff --git a/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/httpclient/HttpClientDemo.java b/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/httpclient/HttpClientDemo.java new file mode 100644 index 00000000..4487e859 --- /dev/null +++ b/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/httpclient/HttpClientDemo.java @@ -0,0 +1,78 @@ +package io.github.kimmking.gateway.outbound.httpclient; + +import org.apache.http.HttpEntity; +import org.apache.http.NameValuePair; +import org.apache.http.client.ClientProtocolException; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.utils.URIBuilder; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.util.EntityUtils; + +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.ArrayList; +import java.util.List; + +public class HttpClientDemo { + + public static void main(String[] args) { + CloseableHttpClient httpClient = HttpClientBuilder.create().build(); + + URI uri = null; + try { + List params = new ArrayList<>(); +// params.add(new BasicNameValuePair("name", "&")); +// params.add(new BasicNameValuePair("age", "18")); + uri = new URIBuilder().setScheme("http").setHost("localhost") + .setPort(8088).setPath("/api/hello") + .setParameters(params).build(); + } catch (URISyntaxException e1) { + e1.printStackTrace(); + } + HttpGet httpGet = new HttpGet(uri); + + CloseableHttpResponse response = null; + try { + RequestConfig requestConfig = RequestConfig.custom() + // 设置连接超时时间(单位毫秒) + .setConnectTimeout(5000) + // 设置请求超时时间(单位毫秒) + .setConnectionRequestTimeout(5000) + // socket读写超时时间(单位毫秒) + .setSocketTimeout(5000) + // 设置是否允许重定向(默认为true) + .setRedirectsEnabled(true).build(); + + httpGet.setConfig(requestConfig); + + response = httpClient.execute(httpGet); + + HttpEntity responseEntity = response.getEntity(); + System.out.println("响应状态为:" + response.getStatusLine()); + if (responseEntity != null) { + System.out.println("响应内容长度为:" + responseEntity.getContentLength()); + System.out.println("响应内容为:" + EntityUtils.toString(responseEntity)); + } + } catch (ClientProtocolException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } finally { + try { + if (httpClient != null) { + httpClient.close(); + } + if (response != null) { + response.close(); + } + } catch (IOException e) { + e.printStackTrace(); + } + } + + } +} diff --git a/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/httpclient/HttpClientOutboundHandler.java b/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/httpclient/HttpClientOutboundHandler.java new file mode 100644 index 00000000..5fdb8af4 --- /dev/null +++ b/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/httpclient/HttpClientOutboundHandler.java @@ -0,0 +1,134 @@ +package io.github.kimmking.gateway.outbound.httpclient; + +import io.netty.buffer.Unpooled; +import io.netty.channel.ChannelFutureListener; +import io.netty.channel.ChannelHandlerContext; +import io.netty.handler.codec.http.DefaultFullHttpResponse; +import io.netty.handler.codec.http.FullHttpRequest; +import io.netty.handler.codec.http.FullHttpResponse; +import io.netty.handler.codec.http.HttpUtil; +import org.apache.http.HttpEntity; +import org.apache.http.HttpResponse; +import org.apache.http.NameValuePair; +import org.apache.http.client.ClientProtocolException; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.utils.URIBuilder; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.util.EntityUtils; + +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.ArrayList; +import java.util.List; + +import static io.netty.handler.codec.http.HttpResponseStatus.NO_CONTENT; +import static io.netty.handler.codec.http.HttpResponseStatus.OK; +import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1; + +public class HttpClientOutboundHandler { + CloseableHttpClient httpClient = HttpClientBuilder.create().build(); + private String backendUrl; + + public HttpClientOutboundHandler(String backendUrl){ + this.backendUrl = backendUrl.endsWith("/")?backendUrl.substring(0,backendUrl.length()-1):backendUrl; + } + + public void handle(FullHttpRequest fullRequest, ChannelHandlerContext ctx) { + URI uri = null; + try { + List params = new ArrayList<>(); +// params.add(new BasicNameValuePair("name", "&")); +// params.add(new BasicNameValuePair("age", "18")); + uri = new URIBuilder(backendUrl).setParameters(params).build(); + } catch (URISyntaxException e1) { + e1.printStackTrace(); + } + HttpGet httpGet = new HttpGet(uri); + CloseableHttpResponse response = null; + try { + RequestConfig requestConfig = RequestConfig.custom() + // 设置连接超时时间(单位毫秒) + .setConnectTimeout(5000) + // 设置请求超时时间(单位毫秒) + .setConnectionRequestTimeout(5000) + // socket读写超时时间(单位毫秒) + .setSocketTimeout(5000) + // 设置是否允许重定向(默认为true) + .setRedirectsEnabled(true).build(); + + httpGet.setConfig(requestConfig); + + response = httpClient.execute(httpGet); + + handleResponse(fullRequest, ctx, response); + } catch (ClientProtocolException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } catch (Exception e) { + e.printStackTrace(); + } finally { + try { + if (httpClient != null) { + httpClient.close(); + } + if (response != null) { + response.close(); + } + } catch (IOException e) { + e.printStackTrace(); + } + + } + } + + private void handleResponse(final FullHttpRequest fullRequest, final ChannelHandlerContext ctx, final HttpResponse endpointResponse) throws Exception { + FullHttpResponse response = null; + try { +// String value = "hello,kimmking"; +// response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(value.getBytes("UTF-8"))); +// response.headers().set("Content-Type", "application/json"); +// response.headers().setInt("Content-Length", response.content().readableBytes()); + + + byte[] body = EntityUtils.toByteArray(endpointResponse.getEntity()); +// System.out.println(new String(body)); +// System.out.println(body.length); + + response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(body)); + response.headers().set("Content-Type", "application/json"); + response.headers().setInt("Content-Length", Integer.parseInt(endpointResponse.getFirstHeader("Content-Length").getValue())); + +// for (Header e : endpointResponse.getAllHeaders()) { +// //response.headers().set(e.getName(),e.getValue()); +// System.out.println(e.getName() + " => " + e.getValue()); +// } + + } catch (Exception e) { + e.printStackTrace(); + response = new DefaultFullHttpResponse(HTTP_1_1, NO_CONTENT); + exceptionCaught(ctx, e); + } finally { + if (fullRequest != null) { + if (!HttpUtil.isKeepAlive(fullRequest)) { + ctx.write(response).addListener(ChannelFutureListener.CLOSE); + } else { + //response.headers().set(CONNECTION, KEEP_ALIVE); + ctx.write(response); + } + } + ctx.flush(); + //ctx.close(); + } + + } + + public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { + cause.printStackTrace(); + ctx.close(); + } +} diff --git a/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/httpclient4/HttpOutboundHandler.java b/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/httpclient4/HttpOutboundHandler.java index 856dc168..94ba1f9d 100644 --- a/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/httpclient4/HttpOutboundHandler.java +++ b/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/httpclient4/HttpOutboundHandler.java @@ -1,6 +1,7 @@ package io.github.kimmking.gateway.outbound.httpclient4; +import io.github.kimmking.gateway.filter.HeaderFilter; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; @@ -17,6 +18,7 @@ import org.apache.http.protocol.HTTP; import org.apache.http.util.EntityUtils; +import java.util.Map; import java.util.concurrent.*; import static io.netty.handler.codec.http.HttpResponseStatus.NO_CONTENT; @@ -63,6 +65,10 @@ private void fetchGet(final FullHttpRequest inbound, final ChannelHandlerContext final HttpGet httpGet = new HttpGet(url); //httpGet.setHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE); httpGet.setHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE); + for(Map.Entry e : inbound.headers().entries()){ + System.out.println(e.getKey() + " => " + e.getValue()); + httpGet.setHeader(e.getKey(), e.getValue()); + } httpclient.execute(httpGet, new FutureCallback() { @Override public void completed(final HttpResponse endpointResponse) { diff --git a/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/netty4/NettyHttpClient.java b/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/netty4/NettyHttpClient.java index 79aeb148..a23fa4a6 100644 --- a/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/netty4/NettyHttpClient.java +++ b/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/netty4/NettyHttpClient.java @@ -1,51 +1,47 @@ -//package io.github.kimmking.gateway.outbound; -// -//import io.netty.bootstrap.Bootstrap; -//import io.netty.channel.ChannelFuture; -//import io.netty.channel.ChannelInitializer; -//import io.netty.channel.ChannelOption; -//import io.netty.channel.EventLoopGroup; -//import io.netty.channel.nio.NioEventLoopGroup; -//import io.netty.channel.socket.SocketChannel; -//import io.netty.channel.socket.nio.NioSocketChannel; -//import io.netty.handler.codec.http.HttpRequestEncoder; -//import io.netty.handler.codec.http.HttpResponseDecoder; -// -//public class NettyHttpClient { -// public void connect(String host, int port) throws Exception { -// EventLoopGroup workerGroup = new NioEventLoopGroup(); -// -// try { -// Bootstrap b = new Bootstrap(); -// b.group(workerGroup); -// b.channel(NioSocketChannel.class); -// b.option(ChannelOption.SO_KEEPALIVE, true); -// b.handler(new ChannelInitializer() { -// @Override -// public void initChannel(SocketChannel ch) throws Exception { -// // 客户端接收到的是httpResponse响应,所以要使用HttpResponseDecoder进行解码 -// ch.pipeline().addLast(new HttpResponseDecoder()); -// 客户端发送的是httprequest,所以要使用HttpRequestEncoder进行编码 -// ch.pipeline().addLast(new HttpRequestEncoder()); -// ch.pipeline().addLast(new HttpClientOutboundHandler()); -// } -// }); -// -// // Start the client. -// ChannelFuture f = b.connect(host, port).sync(); -// -// -// f.channel().write(request); -// f.channel().flush(); -// f.channel().closeFuture().sync(); -// } finally { -// workerGroup.shutdownGracefully(); -// } -// -// } -// -// public static void main(String[] args) throws Exception { -// NettyHttpClient client = new NettyHttpClient(); -// client.connect("127.0.0.1", 8844); -// } -//} \ No newline at end of file +package io.github.kimmking.gateway.outbound.netty4; + +import io.netty.bootstrap.Bootstrap; +import io.netty.channel.*; +import io.netty.channel.nio.NioEventLoopGroup; +import io.netty.channel.socket.SocketChannel; +import io.netty.channel.socket.nio.NioSocketChannel; +import io.netty.handler.codec.http.FullHttpRequest; +import io.netty.handler.codec.http.HttpRequestEncoder; +import io.netty.handler.codec.http.HttpResponseDecoder; + +public class NettyHttpClient { + public void connect(String host, int port, FullHttpRequest fullRequest, ChannelHandlerContext ctx) throws Exception { + EventLoopGroup workerGroup = new NioEventLoopGroup(); + + try { + Bootstrap b = new Bootstrap(); + b.group(workerGroup); + b.channel(NioSocketChannel.class); + b.option(ChannelOption.SO_KEEPALIVE, true); + b.handler(new ChannelInitializer() { + @Override + public void initChannel(SocketChannel ch) throws Exception { + // 客户端接收到的是httpResponse响应,所以要使用HttpResponseDecoder进行解码 + ch.pipeline().addLast(new HttpResponseDecoder()); + // 客户端发送的是httprequest,所以要使用HttpRequestEncoder进行编码 + ch.pipeline().addLast(new HttpRequestEncoder()); + ch.pipeline().addLast(new NettyHttpClientOutboundHandler(fullRequest, ctx)); + } + }); + + // Start the client. + ChannelFuture f = b.connect(host, port).sync(); + f.channel().write("request"); + f.channel().flush(); + f.channel().closeFuture().sync(); + } finally { + workerGroup.shutdownGracefully(); + } + + } + + public static void main(String[] args) throws Exception { + NettyHttpClient client = new NettyHttpClient(); +// client.connect("127.0.0.1", 8803); + } +} \ No newline at end of file diff --git a/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/netty4/NettyHttpClientOutboundHandler.java b/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/netty4/NettyHttpClientOutboundHandler.java index 6730cd5a..24c97f3b 100644 --- a/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/netty4/NettyHttpClientOutboundHandler.java +++ b/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/netty4/NettyHttpClientOutboundHandler.java @@ -1,10 +1,28 @@ package io.github.kimmking.gateway.outbound.netty4; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; +import io.netty.handler.codec.http.DefaultFullHttpResponse; +import io.netty.handler.codec.http.FullHttpRequest; +import io.netty.handler.codec.http.FullHttpResponse; +import io.netty.handler.codec.http.HttpUtil; +import org.apache.http.util.EntityUtils; + +import static io.netty.handler.codec.http.HttpResponseStatus.NO_CONTENT; +import static io.netty.handler.codec.http.HttpResponseStatus.OK; +import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1; public class NettyHttpClientOutboundHandler extends ChannelInboundHandlerAdapter { - + private FullHttpRequest gwFullHttpRequest; + private ChannelHandlerContext gwChannelHandlerContext; + public NettyHttpClientOutboundHandler(FullHttpRequest fullRequest, ChannelHandlerContext ctx) { + gwFullHttpRequest = fullRequest; + gwChannelHandlerContext = ctx; + } + @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { @@ -15,8 +33,44 @@ public void channelActive(ChannelHandlerContext ctx) @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { - - - + ByteBuf bb = (ByteBuf)msg; + FullHttpResponse response = null; + try { +// String value = "hello,kimmking"; +// response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(value.getBytes("UTF-8"))); +// response.headers().set("Content-Type", "application/json"); +// response.headers().setInt("Content-Length", response.content().readableBytes()); + + byte[] body = new byte[bb.readableBytes()]; + // 将buf中的数据读取到数组中 + bb.readBytes(body); +// System.out.println(new String(body)); +// System.out.println(body.length); + + response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(body)); + response.headers().set("Content-Type", "application/json"); + +// for (Header e : endpointResponse.getAllHeaders()) { +// //response.headers().set(e.getName(),e.getValue()); +// System.out.println(e.getName() + " => " + e.getValue()); +// } + + } catch (Exception e) { + e.printStackTrace(); + response = new DefaultFullHttpResponse(HTTP_1_1, NO_CONTENT); + exceptionCaught(ctx, e); + } finally { + if (gwFullHttpRequest != null) { + if (!HttpUtil.isKeepAlive(gwFullHttpRequest)) { + ctx.write(response).addListener(ChannelFutureListener.CLOSE); + } else { + //response.headers().set(CONNECTION, KEEP_ALIVE); + ctx.write(response); + } + } + ctx.flush(); + //ctx.close(); + } + } } \ No newline at end of file diff --git a/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/netty4/NettyOutboundHandler.java b/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/netty4/NettyOutboundHandler.java new file mode 100644 index 00000000..3b524216 --- /dev/null +++ b/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/netty4/NettyOutboundHandler.java @@ -0,0 +1,24 @@ +package io.github.kimmking.gateway.outbound.netty4; + +import io.netty.channel.ChannelHandlerContext; +import io.netty.handler.codec.http.FullHttpRequest; + +public class NettyOutboundHandler { + private String host; + private int port; + NettyHttpClient client = new NettyHttpClient(); + public NettyOutboundHandler(String backendUrl) { + backendUrl = backendUrl.endsWith("/")?backendUrl.substring(0,backendUrl.length()-1):backendUrl; + String[] backend = backendUrl.split(":"); + host = "127.0.0.1"; + port = 8803; + } + + public void handle(FullHttpRequest fullRequest, ChannelHandlerContext ctx) { + try { + client.connect(host, port, fullRequest, ctx); + } catch (Exception e) { + e.printStackTrace(); + } + } +} diff --git a/03concurrency/0301/src/main/java/java0/conc0303/Homework03.java b/03concurrency/0301/src/main/java/java0/conc0303/Homework03.java index 3e64fc85..2f146cda 100644 --- a/03concurrency/0301/src/main/java/java0/conc0303/Homework03.java +++ b/03concurrency/0301/src/main/java/java0/conc0303/Homework03.java @@ -1,5 +1,8 @@ package java0.conc0303; +import java.util.Random; +import java.util.concurrent.*; + /** * 本周作业:(必做)思考有多少种方式,在main函数启动一个新线程或线程池, * 异步运行一个方法,拿到这个方法的返回值后,退出主线程? @@ -9,17 +12,37 @@ */ public class Homework03 { - public static void main(String[] args) { + public static void main(String[] args) throws ExecutionException, InterruptedException { long start=System.currentTimeMillis(); // 在这里创建一个线程或线程池, // 异步执行 下面方法 - - int result = sum(); //这是得到的返回值 - + int result = CompletableFuture.supplyAsync(()-> { + System.out.println("1.CompletableFuture"); + return sum(); + }).join();; // 确保 拿到result 并输出 System.out.println("异步计算结果为:"+result); - + FutureTask task = new FutureTask(new Callable() { + @Override + public Integer call() throws Exception { + System.out.println("2.FutureTask"); + return sum(); + } + }); + new Thread(task).start(); + System.out.println("异步计算结果为:"+task.get()); + ExecutorService executor = Executors.newSingleThreadExecutor(); + Future fresult = executor.submit(new Callable() { + public Integer call() throws Exception { + System.out.println("3.Future"); + return sum(); + } + }); + executor.shutdown(); + System.out.println("异步计算结果为:"+fresult.get()); + + System.out.println("使用时间:"+ (System.currentTimeMillis()-start) + " ms"); // 然后退出main线程