From 73f9ec5b682bf3dc55d6a4ed2d0a7605dcc6daff Mon Sep 17 00:00:00 2001 From: tn <1445763190@qq.com> Date: Sat, 31 Oct 2020 14:51:04 +0800 Subject: [PATCH 01/20] =?UTF-8?q?=E5=91=A8=E5=9B=9B=E4=BD=9C=E4=B8=9A?= =?UTF-8?q?=EF=BC=9A=E6=95=B4=E5=90=88=E4=BD=A0=E4=B8=8A=E6=AC=A1=E4=BD=9C?= =?UTF-8?q?=E4=B8=9A=E7=9A=84httpclient/okhttp?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/io/github/tn/http/HttpClient.java | 80 +++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 02nio/nio02/src/main/java/io/github/tn/http/HttpClient.java diff --git a/02nio/nio02/src/main/java/io/github/tn/http/HttpClient.java b/02nio/nio02/src/main/java/io/github/tn/http/HttpClient.java new file mode 100644 index 00000000..ff78b88e --- /dev/null +++ b/02nio/nio02/src/main/java/io/github/tn/http/HttpClient.java @@ -0,0 +1,80 @@ +package io.github.tn.http; + +import org.apache.http.HttpEntity; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.util.EntityUtils; + +import java.io.IOException; +import java.io.PrintWriter; +import java.net.ServerSocket; +import java.net.Socket; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +/** + * + * 周四作业:整合你上次作业的httpclient/okhttp + * @author tn + * @version 1 + * @ClassName HttpClient + * @description 访问http + * @date 2020/10/27 21:25 + */ +public class HttpClient { + + + //server + public static void main(String[] args) throws IOException { + ExecutorService executorService = Executors.newFixedThreadPool(40); + final ServerSocket serverSocket = new ServerSocket(8803); + while (true) { + try { + final Socket socket = serverSocket.accept(); + executorService.execute(() -> service(socket)); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + //service + private static void service(Socket socket) { + try { + PrintWriter printWriter = new PrintWriter(socket.getOutputStream(), true); + printWriter.println("HTTP/1.1 200 OK"); + printWriter.println("Content-Type:text/html;charset=utf-8"); + String body = requset(); + printWriter.println("Content-Length:" + body.getBytes().length); + printWriter.println(); + printWriter.write(body); + printWriter.close(); + socket.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + + // invoking + private static String requset(){ + HttpGet httpGet = new HttpGet("http://localhost:8801/test"); + try(CloseableHttpClient httpClient = HttpClients.createDefault(); + CloseableHttpResponse resp = httpClient.execute(httpGet) ) { + if(resp.getStatusLine().getStatusCode()==200){ + HttpEntity body = resp.getEntity(); + //使用工具类EntityUtils,从响应中取出实体表示的内容并转换成字符串 + String data = EntityUtils.toString(body, "utf-8"); + return data; + } + }catch (Exception e){ + System.err.println("接口调用失败"); + } + return null; + } + + + +} From d5cb4340749053b21acf74221624f59d6b91d97b Mon Sep 17 00:00:00 2001 From: tn <1445763190@qq.com> Date: Sat, 31 Oct 2020 14:53:23 +0800 Subject: [PATCH 02/20] =?UTF-8?q?=E5=91=A8=E5=9B=9B=E4=BD=9C=E4=B8=9A?= =?UTF-8?q?=EF=BC=9A=E6=95=B4=E5=90=88=E4=BD=A0=E4=B8=8A=E6=AC=A1=E4=BD=9C?= =?UTF-8?q?=E4=B8=9A=E7=9A=84httpclient/okhttp?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- 02nio/nio02/src/main/java/io/github/tn/http/HttpClient.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/02nio/nio02/src/main/java/io/github/tn/http/HttpClient.java b/02nio/nio02/src/main/java/io/github/tn/http/HttpClient.java index ff78b88e..d96d28af 100644 --- a/02nio/nio02/src/main/java/io/github/tn/http/HttpClient.java +++ b/02nio/nio02/src/main/java/io/github/tn/http/HttpClient.java @@ -29,7 +29,7 @@ public class HttpClient { //server public static void main(String[] args) throws IOException { ExecutorService executorService = Executors.newFixedThreadPool(40); - final ServerSocket serverSocket = new ServerSocket(8803); + final ServerSocket serverSocket = new ServerSocket(1212); while (true) { try { final Socket socket = serverSocket.accept(); From f115fca5e6b0f0a8dd7fc98a9f20a28bc66b5e93 Mon Sep 17 00:00:00 2001 From: tn <1445763190@qq.com> Date: Sat, 31 Oct 2020 14:54:20 +0800 Subject: [PATCH 03/20] =?UTF-8?q?=E5=91=A8=E5=9B=9B=E4=BD=9C=E4=B8=9A?= =?UTF-8?q?=EF=BC=9A=E6=95=B4=E5=90=88=E4=BD=A0=E4=B8=8A=E6=AC=A1=E4=BD=9C?= =?UTF-8?q?=E4=B8=9A=E7=9A=84httpclient/okhttp?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- 02nio/nio02/src/main/java/io/github/tn/http/HttpClient.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/02nio/nio02/src/main/java/io/github/tn/http/HttpClient.java b/02nio/nio02/src/main/java/io/github/tn/http/HttpClient.java index d96d28af..8c27a1c1 100644 --- a/02nio/nio02/src/main/java/io/github/tn/http/HttpClient.java +++ b/02nio/nio02/src/main/java/io/github/tn/http/HttpClient.java @@ -72,7 +72,7 @@ private static String requset(){ }catch (Exception e){ System.err.println("接口调用失败"); } - return null; + return "接口调用失败"; } From 499d728ea7e5a9b880b9362682d7d173ae6d1edf Mon Sep 17 00:00:00 2001 From: tn <1445763190@qq.com> Date: Sat, 31 Oct 2020 15:17:23 +0800 Subject: [PATCH 04/20] =?UTF-8?q?=E5=91=A8=E5=9B=9B=E4=BD=9C=E4=B8=9A?= =?UTF-8?q?=EF=BC=88=E5=8F=AF=E9=80=89=EF=BC=89:=E4=BD=BF=E7=94=A8netty?= =?UTF-8?q?=E5=AE=9E=E7=8E=B0=E5=90=8E=E7=AB=AFhttp=E8=AE=BF=E9=97=AE?= =?UTF-8?q?=EF=BC=88=E4=BB=A3=E6=9B=BF=E4=B8=8A=E4=B8=80=E6=AD=A5=E9=AA=A4?= =?UTF-8?q?=EF=BC=89=EF=BC=9B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../tn/gateway/TNettyServerApplication.java | 34 +++++++ .../gateway/inbound/HttpInboundHandler.java | 41 +++++++++ .../inbound/HttpInboundInitializer.java | 24 +++++ .../tn/gateway/inbound/HttpInboundServer.java | 57 ++++++++++++ .../gateway/outbound/HttpOutboundHandler.java | 89 +++++++++++++++++++ 5 files changed, 245 insertions(+) create mode 100644 02nio/nio02/src/main/java/io/github/tn/gateway/TNettyServerApplication.java create mode 100644 02nio/nio02/src/main/java/io/github/tn/gateway/inbound/HttpInboundHandler.java create mode 100644 02nio/nio02/src/main/java/io/github/tn/gateway/inbound/HttpInboundInitializer.java create mode 100644 02nio/nio02/src/main/java/io/github/tn/gateway/inbound/HttpInboundServer.java create mode 100644 02nio/nio02/src/main/java/io/github/tn/gateway/outbound/HttpOutboundHandler.java diff --git a/02nio/nio02/src/main/java/io/github/tn/gateway/TNettyServerApplication.java b/02nio/nio02/src/main/java/io/github/tn/gateway/TNettyServerApplication.java new file mode 100644 index 00000000..ce30d26e --- /dev/null +++ b/02nio/nio02/src/main/java/io/github/tn/gateway/TNettyServerApplication.java @@ -0,0 +1,34 @@ +package io.github.tn.gateway; + + +import io.github.tn.gateway.inbound.HttpInboundServer; + +/** + * gateway 启动类 + */ +public class TNettyServerApplication { + + //项目名 + public final static String GATEWAY_NAME = "NIOGateway"; + //版本 + public final static String GATEWAY_VERSION = "1.0.0"; + + public static void main(String[] args) { + String proxyServer = System.getProperty("proxyServer","http://localhost:8801/test"); + String proxyPort = System.getProperty("proxyPort","8888"); + + // http://localhost:8888/api/hello ==> gateway API + // http://localhost:8088/api/hello ==> backend service + + int port = Integer.parseInt(proxyPort); + System.out.println(GATEWAY_NAME + " " + GATEWAY_VERSION +" starting..."); + // netty 启动 + HttpInboundServer server = new HttpInboundServer(port, proxyServer); + System.out.println(GATEWAY_NAME + " " + GATEWAY_VERSION +" started at http://localhost:" + port + " for server:" + proxyServer); + try { + server.run(); + }catch (Exception ex){ + ex.printStackTrace(); + } + } +} diff --git a/02nio/nio02/src/main/java/io/github/tn/gateway/inbound/HttpInboundHandler.java b/02nio/nio02/src/main/java/io/github/tn/gateway/inbound/HttpInboundHandler.java new file mode 100644 index 00000000..0ac7355d --- /dev/null +++ b/02nio/nio02/src/main/java/io/github/tn/gateway/inbound/HttpInboundHandler.java @@ -0,0 +1,41 @@ +package io.github.tn.gateway.inbound; + +import io.github.tn.gateway.outbound.HttpOutboundHandler; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelInboundHandlerAdapter; +import io.netty.handler.codec.http.FullHttpRequest; +import io.netty.util.ReferenceCountUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class HttpInboundHandler extends ChannelInboundHandlerAdapter { + + private static Logger logger = LoggerFactory.getLogger(HttpInboundHandler.class); + private final String proxyServer; + private HttpOutboundHandler handler; + + public HttpInboundHandler(String proxyServer) { + this.proxyServer = proxyServer; + handler = new HttpOutboundHandler(this.proxyServer); + } + + @Override + public void channelReadComplete(ChannelHandlerContext ctx) { + ctx.flush(); + } + + @Override + public void channelRead(ChannelHandlerContext ctx, Object msg) { + try { + //logger.info("channelRead流量接口请求开始,时间为{}", startTime); + FullHttpRequest fullRequest = (FullHttpRequest) msg; + handler.requset(fullRequest, ctx); + } catch(Exception e) { + e.printStackTrace(); + } finally { + ReferenceCountUtil.release(msg); + } + } + + +} diff --git a/02nio/nio02/src/main/java/io/github/tn/gateway/inbound/HttpInboundInitializer.java b/02nio/nio02/src/main/java/io/github/tn/gateway/inbound/HttpInboundInitializer.java new file mode 100644 index 00000000..24caf9ca --- /dev/null +++ b/02nio/nio02/src/main/java/io/github/tn/gateway/inbound/HttpInboundInitializer.java @@ -0,0 +1,24 @@ +package io.github.tn.gateway.inbound; + +import io.netty.channel.ChannelInitializer; +import io.netty.channel.ChannelPipeline; +import io.netty.channel.socket.SocketChannel; +import io.netty.handler.codec.http.HttpObjectAggregator; +import io.netty.handler.codec.http.HttpServerCodec; + +public class HttpInboundInitializer extends ChannelInitializer { + + private String proxyServer; + + public HttpInboundInitializer(String proxyServer) { + this.proxyServer = proxyServer; + } + + @Override + public void initChannel(SocketChannel ch) { + ChannelPipeline p = ch.pipeline(); + p.addLast(new HttpServerCodec()); + p.addLast(new HttpObjectAggregator(1024 * 1024)); + p.addLast(new HttpInboundHandler(this.proxyServer)); + } +} diff --git a/02nio/nio02/src/main/java/io/github/tn/gateway/inbound/HttpInboundServer.java b/02nio/nio02/src/main/java/io/github/tn/gateway/inbound/HttpInboundServer.java new file mode 100644 index 00000000..d22dc975 --- /dev/null +++ b/02nio/nio02/src/main/java/io/github/tn/gateway/inbound/HttpInboundServer.java @@ -0,0 +1,57 @@ +package io.github.tn.gateway.inbound; + +import io.netty.bootstrap.ServerBootstrap; +import io.netty.buffer.PooledByteBufAllocator; +import io.netty.channel.Channel; +import io.netty.channel.ChannelOption; +import io.netty.channel.EventLoopGroup; +import io.netty.channel.epoll.EpollChannelOption; +import io.netty.channel.nio.NioEventLoopGroup; +import io.netty.channel.socket.nio.NioServerSocketChannel; +import io.netty.handler.logging.LogLevel; +import io.netty.handler.logging.LoggingHandler; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +public class HttpInboundServer { + private static Logger logger = LoggerFactory.getLogger(HttpInboundServer.class); + + private int port; + + private String proxyServer; + + public HttpInboundServer(int port, String proxyServer) { + this.port=port; + this.proxyServer = proxyServer; + } + + public void run() throws Exception { + + EventLoopGroup bossGroup = new NioEventLoopGroup(1); + EventLoopGroup workerGroup = new NioEventLoopGroup(16); + + try { + ServerBootstrap b = new ServerBootstrap(); + b.option(ChannelOption.SO_BACKLOG, 128) + .option(ChannelOption.TCP_NODELAY, true) + .option(ChannelOption.SO_KEEPALIVE, true) + .option(ChannelOption.SO_REUSEADDR, true) + .option(ChannelOption.SO_RCVBUF, 32 * 1024) + .option(ChannelOption.SO_SNDBUF, 32 * 1024) + .option(EpollChannelOption.SO_REUSEPORT, true) + .childOption(ChannelOption.SO_KEEPALIVE, true) + .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); + + b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) + .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new HttpInboundInitializer(this.proxyServer)); + + Channel ch = b.bind(port).sync().channel(); + logger.info("开启netty http服务器,监听地址和端口为 http://127.0.0.1:" + port + '/'); + ch.closeFuture().sync(); + } finally { + bossGroup.shutdownGracefully(); + workerGroup.shutdownGracefully(); + } + } +} diff --git a/02nio/nio02/src/main/java/io/github/tn/gateway/outbound/HttpOutboundHandler.java b/02nio/nio02/src/main/java/io/github/tn/gateway/outbound/HttpOutboundHandler.java new file mode 100644 index 00000000..dce3a458 --- /dev/null +++ b/02nio/nio02/src/main/java/io/github/tn/gateway/outbound/HttpOutboundHandler.java @@ -0,0 +1,89 @@ +package io.github.tn.gateway.outbound; + +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.HttpResponse; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.protocol.HTTP; +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; + +/** + * @author tn + * @version 1 + * @ClassName HttpOutboundHandler + * @description httpClient + * @date 2020/10/31 14:59 + */ +public class HttpOutboundHandler { + private String backendUrl; + + public HttpOutboundHandler(String backendUrl) { + this.backendUrl = backendUrl; + } + + // invoking + public void requset(FullHttpRequest fullRequest, ChannelHandlerContext ctx){ + final String url = this.backendUrl + fullRequest.uri(); + invoking(fullRequest, ctx, url); + } + + + // invoking + private String invoking(final FullHttpRequest inbound, final ChannelHandlerContext ctx, final String url){ + HttpGet httpGet = new HttpGet(url); + httpGet.setHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE); + try(CloseableHttpClient httpClient = HttpClients.createDefault(); + CloseableHttpResponse resp = httpClient.execute(httpGet) ) { + handleResponse(inbound, ctx, resp); + }catch (Exception e){ + System.err.println("接口调用失败"); + } + return "接口调用失败"; + } + + + private void handleResponse(final FullHttpRequest fullRequest, final ChannelHandlerContext ctx, final HttpResponse endpointResponse) throws Exception { + FullHttpResponse response = null; + try { + + byte[] body = EntityUtils.toByteArray(endpointResponse.getEntity()); + + 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())); + + } 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 { + ctx.write(response); + } + } + ctx.flush(); + } + + } + + public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { + cause.printStackTrace(); + ctx.close(); + } + +} From d33e1cdf803eb377bd2c0cd93c36bc93eb43dccc Mon Sep 17 00:00:00 2001 From: tn <1445763190@qq.com> Date: Sat, 31 Oct 2020 15:21:43 +0800 Subject: [PATCH 05/20] =?UTF-8?q?=E5=91=A8=E5=9B=9B=E4=BD=9C=E4=B8=9A?= =?UTF-8?q?=EF=BC=88=E5=8F=AF=E9=80=89=EF=BC=89:=E4=BD=BF=E7=94=A8netty?= =?UTF-8?q?=E5=AE=9E=E7=8E=B0=E5=90=8E=E7=AB=AFhttp=E8=AE=BF=E9=97=AE?= =?UTF-8?q?=EF=BC=88=E4=BB=A3=E6=9B=BF=E4=B8=8A=E4=B8=80=E6=AD=A5=E9=AA=A4?= =?UTF-8?q?=EF=BC=89=EF=BC=9B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/io/github/tn/gateway/outbound/HttpOutboundHandler.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/02nio/nio02/src/main/java/io/github/tn/gateway/outbound/HttpOutboundHandler.java b/02nio/nio02/src/main/java/io/github/tn/gateway/outbound/HttpOutboundHandler.java index dce3a458..ef6a86b5 100644 --- a/02nio/nio02/src/main/java/io/github/tn/gateway/outbound/HttpOutboundHandler.java +++ b/02nio/nio02/src/main/java/io/github/tn/gateway/outbound/HttpOutboundHandler.java @@ -54,6 +54,7 @@ private String invoking(final FullHttpRequest inbound, final ChannelHandlerConte } + // Response private void handleResponse(final FullHttpRequest fullRequest, final ChannelHandlerContext ctx, final HttpResponse endpointResponse) throws Exception { FullHttpResponse response = null; try { @@ -81,6 +82,7 @@ private void handleResponse(final FullHttpRequest fullRequest, final ChannelHand } + // 关流 public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { cause.printStackTrace(); ctx.close(); From 80a5ff89619d0c57232391bd3a6eee5830c0d6c0 Mon Sep 17 00:00:00 2001 From: tn <1445763190@qq.com> Date: Tue, 3 Nov 2020 20:14:52 +0800 Subject: [PATCH 06/20] =?UTF-8?q?=E6=95=B4=E5=90=88=E4=BD=A0=E4=B8=8A?= =?UTF-8?q?=E6=AC=A1=E4=BD=9C=E4=B8=9A=E7=9A=84httpclient/okhttp?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../main/java/io/github/tn/{http => week03_1}/HttpClient.java | 2 +- .../tn/{gateway => week03_2}/TNettyServerApplication.java | 4 ++-- .../tn/{gateway => week03_2}/inbound/HttpInboundHandler.java | 4 ++-- .../{gateway => week03_2}/inbound/HttpInboundInitializer.java | 2 +- .../tn/{gateway => week03_2}/inbound/HttpInboundServer.java | 2 +- .../{gateway => week03_2}/outbound/HttpOutboundHandler.java | 2 +- 6 files changed, 8 insertions(+), 8 deletions(-) rename 02nio/nio02/src/main/java/io/github/tn/{http => week03_1}/HttpClient.java (98%) rename 02nio/nio02/src/main/java/io/github/tn/{gateway => week03_2}/TNettyServerApplication.java (92%) rename 02nio/nio02/src/main/java/io/github/tn/{gateway => week03_2}/inbound/HttpInboundHandler.java (92%) rename 02nio/nio02/src/main/java/io/github/tn/{gateway => week03_2}/inbound/HttpInboundInitializer.java (94%) rename 02nio/nio02/src/main/java/io/github/tn/{gateway => week03_2}/inbound/HttpInboundServer.java (98%) rename 02nio/nio02/src/main/java/io/github/tn/{gateway => week03_2}/outbound/HttpOutboundHandler.java (98%) diff --git a/02nio/nio02/src/main/java/io/github/tn/http/HttpClient.java b/02nio/nio02/src/main/java/io/github/tn/week03_1/HttpClient.java similarity index 98% rename from 02nio/nio02/src/main/java/io/github/tn/http/HttpClient.java rename to 02nio/nio02/src/main/java/io/github/tn/week03_1/HttpClient.java index 8c27a1c1..6813fa53 100644 --- a/02nio/nio02/src/main/java/io/github/tn/http/HttpClient.java +++ b/02nio/nio02/src/main/java/io/github/tn/week03_1/HttpClient.java @@ -1,4 +1,4 @@ -package io.github.tn.http; +package io.github.tn.week03_1; import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; diff --git a/02nio/nio02/src/main/java/io/github/tn/gateway/TNettyServerApplication.java b/02nio/nio02/src/main/java/io/github/tn/week03_2/TNettyServerApplication.java similarity index 92% rename from 02nio/nio02/src/main/java/io/github/tn/gateway/TNettyServerApplication.java rename to 02nio/nio02/src/main/java/io/github/tn/week03_2/TNettyServerApplication.java index ce30d26e..9ae4ee26 100644 --- a/02nio/nio02/src/main/java/io/github/tn/gateway/TNettyServerApplication.java +++ b/02nio/nio02/src/main/java/io/github/tn/week03_2/TNettyServerApplication.java @@ -1,7 +1,7 @@ -package io.github.tn.gateway; +package io.github.tn.week03_2; -import io.github.tn.gateway.inbound.HttpInboundServer; +import io.github.tn.week03_2.inbound.HttpInboundServer; /** * gateway 启动类 diff --git a/02nio/nio02/src/main/java/io/github/tn/gateway/inbound/HttpInboundHandler.java b/02nio/nio02/src/main/java/io/github/tn/week03_2/inbound/HttpInboundHandler.java similarity index 92% rename from 02nio/nio02/src/main/java/io/github/tn/gateway/inbound/HttpInboundHandler.java rename to 02nio/nio02/src/main/java/io/github/tn/week03_2/inbound/HttpInboundHandler.java index 0ac7355d..e2b0a2fc 100644 --- a/02nio/nio02/src/main/java/io/github/tn/gateway/inbound/HttpInboundHandler.java +++ b/02nio/nio02/src/main/java/io/github/tn/week03_2/inbound/HttpInboundHandler.java @@ -1,6 +1,6 @@ -package io.github.tn.gateway.inbound; +package io.github.tn.week03_2.inbound; -import io.github.tn.gateway.outbound.HttpOutboundHandler; +import io.github.tn.week03_2.outbound.HttpOutboundHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.handler.codec.http.FullHttpRequest; diff --git a/02nio/nio02/src/main/java/io/github/tn/gateway/inbound/HttpInboundInitializer.java b/02nio/nio02/src/main/java/io/github/tn/week03_2/inbound/HttpInboundInitializer.java similarity index 94% rename from 02nio/nio02/src/main/java/io/github/tn/gateway/inbound/HttpInboundInitializer.java rename to 02nio/nio02/src/main/java/io/github/tn/week03_2/inbound/HttpInboundInitializer.java index 24caf9ca..2dcf1876 100644 --- a/02nio/nio02/src/main/java/io/github/tn/gateway/inbound/HttpInboundInitializer.java +++ b/02nio/nio02/src/main/java/io/github/tn/week03_2/inbound/HttpInboundInitializer.java @@ -1,4 +1,4 @@ -package io.github.tn.gateway.inbound; +package io.github.tn.week03_2.inbound; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; diff --git a/02nio/nio02/src/main/java/io/github/tn/gateway/inbound/HttpInboundServer.java b/02nio/nio02/src/main/java/io/github/tn/week03_2/inbound/HttpInboundServer.java similarity index 98% rename from 02nio/nio02/src/main/java/io/github/tn/gateway/inbound/HttpInboundServer.java rename to 02nio/nio02/src/main/java/io/github/tn/week03_2/inbound/HttpInboundServer.java index d22dc975..14cf047d 100644 --- a/02nio/nio02/src/main/java/io/github/tn/gateway/inbound/HttpInboundServer.java +++ b/02nio/nio02/src/main/java/io/github/tn/week03_2/inbound/HttpInboundServer.java @@ -1,4 +1,4 @@ -package io.github.tn.gateway.inbound; +package io.github.tn.week03_2.inbound; import io.netty.bootstrap.ServerBootstrap; import io.netty.buffer.PooledByteBufAllocator; diff --git a/02nio/nio02/src/main/java/io/github/tn/gateway/outbound/HttpOutboundHandler.java b/02nio/nio02/src/main/java/io/github/tn/week03_2/outbound/HttpOutboundHandler.java similarity index 98% rename from 02nio/nio02/src/main/java/io/github/tn/gateway/outbound/HttpOutboundHandler.java rename to 02nio/nio02/src/main/java/io/github/tn/week03_2/outbound/HttpOutboundHandler.java index ef6a86b5..fae67ce6 100644 --- a/02nio/nio02/src/main/java/io/github/tn/gateway/outbound/HttpOutboundHandler.java +++ b/02nio/nio02/src/main/java/io/github/tn/week03_2/outbound/HttpOutboundHandler.java @@ -1,4 +1,4 @@ -package io.github.tn.gateway.outbound; +package io.github.tn.week03_2.outbound; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelFutureListener; From 9c64371d1a0a1af2b67d7943e33dafce38389799 Mon Sep 17 00:00:00 2001 From: tn <1445763190@qq.com> Date: Tue, 3 Nov 2020 20:15:43 +0800 Subject: [PATCH 07/20] =?UTF-8?q?=E5=91=A8=E5=9B=9B=E4=BD=9C=E4=B8=9A?= =?UTF-8?q?=EF=BC=88=E5=8F=AF=E9=80=89=EF=BC=89:=E4=BD=BF=E7=94=A8netty?= =?UTF-8?q?=E5=AE=9E=E7=8E=B0=E5=90=8E=E7=AB=AFhttp=E8=AE=BF=E9=97=AE?= =?UTF-8?q?=EF=BC=88=E4=BB=A3=E6=9B=BF=E4=B8=8A=E4=B8=80=E6=AD=A5=E9=AA=A4?= =?UTF-8?q?=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/io/github/tn/week03_2/TNettyServerApplication.java | 2 +- .../java/io/github/tn/week03_2/inbound/HttpInboundHandler.java | 2 +- .../io/github/tn/week03_2/inbound/HttpInboundInitializer.java | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/02nio/nio02/src/main/java/io/github/tn/week03_2/TNettyServerApplication.java b/02nio/nio02/src/main/java/io/github/tn/week03_2/TNettyServerApplication.java index 9ae4ee26..8bfd414e 100644 --- a/02nio/nio02/src/main/java/io/github/tn/week03_2/TNettyServerApplication.java +++ b/02nio/nio02/src/main/java/io/github/tn/week03_2/TNettyServerApplication.java @@ -12,7 +12,7 @@ public class TNettyServerApplication { public final static String GATEWAY_NAME = "NIOGateway"; //版本 public final static String GATEWAY_VERSION = "1.0.0"; - + public static void main(String[] args) { String proxyServer = System.getProperty("proxyServer","http://localhost:8801/test"); String proxyPort = System.getProperty("proxyPort","8888"); diff --git a/02nio/nio02/src/main/java/io/github/tn/week03_2/inbound/HttpInboundHandler.java b/02nio/nio02/src/main/java/io/github/tn/week03_2/inbound/HttpInboundHandler.java index e2b0a2fc..a99b0bd1 100644 --- a/02nio/nio02/src/main/java/io/github/tn/week03_2/inbound/HttpInboundHandler.java +++ b/02nio/nio02/src/main/java/io/github/tn/week03_2/inbound/HttpInboundHandler.java @@ -13,7 +13,7 @@ public class HttpInboundHandler extends ChannelInboundHandlerAdapter { private static Logger logger = LoggerFactory.getLogger(HttpInboundHandler.class); private final String proxyServer; private HttpOutboundHandler handler; - + public HttpInboundHandler(String proxyServer) { this.proxyServer = proxyServer; handler = new HttpOutboundHandler(this.proxyServer); diff --git a/02nio/nio02/src/main/java/io/github/tn/week03_2/inbound/HttpInboundInitializer.java b/02nio/nio02/src/main/java/io/github/tn/week03_2/inbound/HttpInboundInitializer.java index 2dcf1876..dff3a40b 100644 --- a/02nio/nio02/src/main/java/io/github/tn/week03_2/inbound/HttpInboundInitializer.java +++ b/02nio/nio02/src/main/java/io/github/tn/week03_2/inbound/HttpInboundInitializer.java @@ -9,7 +9,7 @@ public class HttpInboundInitializer extends ChannelInitializer { private String proxyServer; - + public HttpInboundInitializer(String proxyServer) { this.proxyServer = proxyServer; } From d02884a3b82abfac6eb04e4ed4485cc214eb114b Mon Sep 17 00:00:00 2001 From: tn <1445763190@qq.com> Date: Thu, 5 Nov 2020 19:33:52 +0800 Subject: [PATCH 08/20] =?UTF-8?q?=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../tn/week03_3/NettyServerApplication.java | 28 ++++ .../tn/week03_3/filter/HttpRequestFilter.java | 10 ++ .../filter/HttpRequestFilterImpl.java | 23 +++ .../week03_3/inbound/HttpInboundHandler.java | 80 ++++++++++ .../inbound/HttpInboundInitializer.java | 28 ++++ .../week03_3/inbound/HttpInboundServer.java | 57 ++++++++ .../httpclient4/HttpOutboundHandler.java | 138 ++++++++++++++++++ .../httpclient4/NamedThreadFactory.java | 32 ++++ .../outbound/netty4/NettyHttpClient.java | 51 +++++++ .../NettyHttpClientOutboundHandler.java | 22 +++ .../okhttp/OkhttpOutboundHandler.java | 4 + .../week03_3/router/HttpEndpointRouter.java | 9 ++ 12 files changed, 482 insertions(+) create mode 100644 02nio/nio02/src/main/java/io/github/tn/week03_3/NettyServerApplication.java create mode 100644 02nio/nio02/src/main/java/io/github/tn/week03_3/filter/HttpRequestFilter.java create mode 100644 02nio/nio02/src/main/java/io/github/tn/week03_3/filter/HttpRequestFilterImpl.java create mode 100644 02nio/nio02/src/main/java/io/github/tn/week03_3/inbound/HttpInboundHandler.java create mode 100644 02nio/nio02/src/main/java/io/github/tn/week03_3/inbound/HttpInboundInitializer.java create mode 100644 02nio/nio02/src/main/java/io/github/tn/week03_3/inbound/HttpInboundServer.java create mode 100644 02nio/nio02/src/main/java/io/github/tn/week03_3/outbound/httpclient4/HttpOutboundHandler.java create mode 100644 02nio/nio02/src/main/java/io/github/tn/week03_3/outbound/httpclient4/NamedThreadFactory.java create mode 100644 02nio/nio02/src/main/java/io/github/tn/week03_3/outbound/netty4/NettyHttpClient.java create mode 100644 02nio/nio02/src/main/java/io/github/tn/week03_3/outbound/netty4/NettyHttpClientOutboundHandler.java create mode 100644 02nio/nio02/src/main/java/io/github/tn/week03_3/outbound/okhttp/OkhttpOutboundHandler.java create mode 100644 02nio/nio02/src/main/java/io/github/tn/week03_3/router/HttpEndpointRouter.java diff --git a/02nio/nio02/src/main/java/io/github/tn/week03_3/NettyServerApplication.java b/02nio/nio02/src/main/java/io/github/tn/week03_3/NettyServerApplication.java new file mode 100644 index 00000000..6540df47 --- /dev/null +++ b/02nio/nio02/src/main/java/io/github/tn/week03_3/NettyServerApplication.java @@ -0,0 +1,28 @@ +package io.github.tn.week03_3; + + +import io.github.tn.week03_3.inbound.HttpInboundServer; + +public class NettyServerApplication { + + public final static String GATEWAY_NAME = "NIOGateway"; + public final static String GATEWAY_VERSION = "1.0.0"; + + public static void main(String[] args) { + String proxyServer = System.getProperty("proxyServer","http://localhost:8801"); + String proxyPort = System.getProperty("proxyPort","8888"); + + // http://localhost:8888/api/hello ==> gateway API + // http://localhost:8088/api/hello ==> backend service + + int port = Integer.parseInt(proxyPort); + System.out.println(GATEWAY_NAME + " " + GATEWAY_VERSION +" starting..."); + HttpInboundServer server = new HttpInboundServer(port, proxyServer); + System.out.println(GATEWAY_NAME + " " + GATEWAY_VERSION +" started at http://localhost:" + port + " for server:" + proxyServer); + try { + server.run(); + }catch (Exception ex){ + ex.printStackTrace(); + } + } +} diff --git a/02nio/nio02/src/main/java/io/github/tn/week03_3/filter/HttpRequestFilter.java b/02nio/nio02/src/main/java/io/github/tn/week03_3/filter/HttpRequestFilter.java new file mode 100644 index 00000000..a733054d --- /dev/null +++ b/02nio/nio02/src/main/java/io/github/tn/week03_3/filter/HttpRequestFilter.java @@ -0,0 +1,10 @@ +package io.github.tn.week03_3.filter; + +import io.netty.channel.ChannelHandlerContext; +import io.netty.handler.codec.http.FullHttpRequest; + +public interface HttpRequestFilter { + + void filter(FullHttpRequest fullRequest, ChannelHandlerContext ctx); + +} diff --git a/02nio/nio02/src/main/java/io/github/tn/week03_3/filter/HttpRequestFilterImpl.java b/02nio/nio02/src/main/java/io/github/tn/week03_3/filter/HttpRequestFilterImpl.java new file mode 100644 index 00000000..4cf397a1 --- /dev/null +++ b/02nio/nio02/src/main/java/io/github/tn/week03_3/filter/HttpRequestFilterImpl.java @@ -0,0 +1,23 @@ +package io.github.tn.week03_3.filter; + +import io.netty.channel.ChannelHandlerContext; +import io.netty.handler.codec.http.FullHttpRequest; + +/** + * @author tn + * @version 1 + * @ClassName HttpRequestFilterimpl + * @description 拦截器 + * @date 2020/11/3 20:16 + */ +public class HttpRequestFilterImpl implements HttpRequestFilter { + + + @Override + public void filter(FullHttpRequest fullRequest, ChannelHandlerContext ctx) { + //如果同名header已存在,则追加至原同名header后面 + fullRequest.headers().add("nio","tanning"); + //如果同名header已存在,则覆盖一个同名header。 +// fullRequest.headers().set("nio","tanning"); + } +} diff --git a/02nio/nio02/src/main/java/io/github/tn/week03_3/inbound/HttpInboundHandler.java b/02nio/nio02/src/main/java/io/github/tn/week03_3/inbound/HttpInboundHandler.java new file mode 100644 index 00000000..23799df1 --- /dev/null +++ b/02nio/nio02/src/main/java/io/github/tn/week03_3/inbound/HttpInboundHandler.java @@ -0,0 +1,80 @@ +package io.github.tn.week03_3.inbound; + +import io.github.tn.week03_3.filter.HttpRequestFilter; +import io.github.tn.week03_3.filter.HttpRequestFilterImpl; +import io.github.tn.week03_3.outbound.httpclient4.HttpOutboundHandler; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelInboundHandlerAdapter; +import io.netty.handler.codec.http.FullHttpRequest; +import io.netty.util.ReferenceCountUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class HttpInboundHandler extends ChannelInboundHandlerAdapter { + + private static Logger logger = LoggerFactory.getLogger(HttpInboundHandler.class); + private final String proxyServer; + private HttpOutboundHandler handler; + private HttpRequestFilter requestFilter; + + public HttpInboundHandler(String proxyServer) { + this.proxyServer = proxyServer; + this.requestFilter = new HttpRequestFilterImpl(); + handler = new HttpOutboundHandler(this.proxyServer); + } + + @Override + public void channelReadComplete(ChannelHandlerContext ctx) { + ctx.flush(); + } + + @Override + 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); +// } + requestFilter.filter(fullRequest,ctx); + handler.handle(fullRequest, ctx); + + } catch(Exception e) { + e.printStackTrace(); + } finally { + ReferenceCountUtil.release(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(); +// } + +} diff --git a/02nio/nio02/src/main/java/io/github/tn/week03_3/inbound/HttpInboundInitializer.java b/02nio/nio02/src/main/java/io/github/tn/week03_3/inbound/HttpInboundInitializer.java new file mode 100644 index 00000000..7d224a96 --- /dev/null +++ b/02nio/nio02/src/main/java/io/github/tn/week03_3/inbound/HttpInboundInitializer.java @@ -0,0 +1,28 @@ +package io.github.tn.week03_3.inbound; + +import io.netty.channel.ChannelInitializer; +import io.netty.channel.ChannelPipeline; +import io.netty.channel.socket.SocketChannel; +import io.netty.handler.codec.http.HttpObjectAggregator; +import io.netty.handler.codec.http.HttpServerCodec; + +public class HttpInboundInitializer extends ChannelInitializer { + + private String proxyServer; + + public HttpInboundInitializer(String proxyServer) { + this.proxyServer = proxyServer; + } + + @Override + public void initChannel(SocketChannel ch) { + ChannelPipeline p = ch.pipeline(); +// if (sslCtx != null) { +// p.addLast(sslCtx.newHandler(ch.alloc())); +// } + p.addLast(new HttpServerCodec()); + //p.addLast(new HttpServerExpectContinueHandler()); + p.addLast(new HttpObjectAggregator(1024 * 1024)); + p.addLast(new HttpInboundHandler(this.proxyServer)); + } +} diff --git a/02nio/nio02/src/main/java/io/github/tn/week03_3/inbound/HttpInboundServer.java b/02nio/nio02/src/main/java/io/github/tn/week03_3/inbound/HttpInboundServer.java new file mode 100644 index 00000000..ebb0d74f --- /dev/null +++ b/02nio/nio02/src/main/java/io/github/tn/week03_3/inbound/HttpInboundServer.java @@ -0,0 +1,57 @@ +package io.github.tn.week03_3.inbound; + +import io.netty.bootstrap.ServerBootstrap; +import io.netty.buffer.PooledByteBufAllocator; +import io.netty.channel.Channel; +import io.netty.channel.ChannelOption; +import io.netty.channel.EventLoopGroup; +import io.netty.channel.epoll.EpollChannelOption; +import io.netty.channel.nio.NioEventLoopGroup; +import io.netty.channel.socket.nio.NioServerSocketChannel; +import io.netty.handler.logging.LogLevel; +import io.netty.handler.logging.LoggingHandler; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +public class HttpInboundServer { + private static Logger logger = LoggerFactory.getLogger(HttpInboundServer.class); + + private int port; + + private String proxyServer; + + public HttpInboundServer(int port, String proxyServer) { + this.port=port; + this.proxyServer = proxyServer; + } + + public void run() throws Exception { + + EventLoopGroup bossGroup = new NioEventLoopGroup(1); + EventLoopGroup workerGroup = new NioEventLoopGroup(16); + + try { + ServerBootstrap b = new ServerBootstrap(); + b.option(ChannelOption.SO_BACKLOG, 128) + .option(ChannelOption.TCP_NODELAY, true) + .option(ChannelOption.SO_KEEPALIVE, true) + .option(ChannelOption.SO_REUSEADDR, true) + .option(ChannelOption.SO_RCVBUF, 32 * 1024) + .option(ChannelOption.SO_SNDBUF, 32 * 1024) + .option(EpollChannelOption.SO_REUSEPORT, true) + .childOption(ChannelOption.SO_KEEPALIVE, true) + .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); + + b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) + .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new HttpInboundInitializer(this.proxyServer)); + + Channel ch = b.bind(port).sync().channel(); + logger.info("开启netty http服务器,监听地址和端口为 http://127.0.0.1:" + port + '/'); + ch.closeFuture().sync(); + } finally { + bossGroup.shutdownGracefully(); + workerGroup.shutdownGracefully(); + } + } +} diff --git a/02nio/nio02/src/main/java/io/github/tn/week03_3/outbound/httpclient4/HttpOutboundHandler.java b/02nio/nio02/src/main/java/io/github/tn/week03_3/outbound/httpclient4/HttpOutboundHandler.java new file mode 100644 index 00000000..42173f93 --- /dev/null +++ b/02nio/nio02/src/main/java/io/github/tn/week03_3/outbound/httpclient4/HttpOutboundHandler.java @@ -0,0 +1,138 @@ +package io.github.tn.week03_3.outbound.httpclient4; + + +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.HttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.concurrent.FutureCallback; +import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; +import org.apache.http.impl.nio.client.HttpAsyncClients; +import org.apache.http.impl.nio.reactor.IOReactorConfig; +import org.apache.http.protocol.HTTP; +import org.apache.http.util.EntityUtils; + +import java.util.concurrent.*; + +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 HttpOutboundHandler { + + private CloseableHttpAsyncClient httpclient; + private ExecutorService proxyService; + private String backendUrl; + + public HttpOutboundHandler(String backendUrl){ + this.backendUrl = backendUrl.endsWith("/")?backendUrl.substring(0,backendUrl.length()-1):backendUrl; + int cores = Runtime.getRuntime().availableProcessors() * 2; + long keepAliveTime = 1000; + int queueSize = 2048; + RejectedExecutionHandler handler = new ThreadPoolExecutor.CallerRunsPolicy();//.DiscardPolicy(); + proxyService = new ThreadPoolExecutor(cores, cores, + keepAliveTime, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(queueSize), + new NamedThreadFactory("proxyService"), handler); + + IOReactorConfig ioConfig = IOReactorConfig.custom() + .setConnectTimeout(1000) + .setSoTimeout(1000) + .setIoThreadCount(cores) + .setRcvBufSize(32 * 1024) + .build(); + + httpclient = HttpAsyncClients.custom().setMaxConnTotal(40) + .setMaxConnPerRoute(8) + .setDefaultIOReactorConfig(ioConfig) + .setKeepAliveStrategy((response,context) -> 6000) + .build(); + httpclient.start(); + } + + public void handle(final FullHttpRequest fullRequest, final ChannelHandlerContext ctx) { + final String url = this.backendUrl + fullRequest.uri(); + proxyService.submit(()->fetchGet(fullRequest, ctx, url)); + } + + private void fetchGet(final FullHttpRequest inbound, final ChannelHandlerContext ctx, final String url) { + final HttpGet httpGet = new HttpGet(url); + //httpGet.setHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE); + httpGet.setHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE); + httpclient.execute(httpGet, new FutureCallback() { + @Override + public void completed(final HttpResponse endpointResponse) { + try { + handleResponse(inbound, ctx, endpointResponse); + } catch (Exception e) { + e.printStackTrace(); + } finally { + + } + } + + @Override + public void failed(final Exception ex) { + httpGet.abort(); + ex.printStackTrace(); + } + + @Override + public void cancelled() { + httpGet.abort(); + } + }); + } + + 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())); +// response.headers().set("nio","tanning"); +// 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/tn/week03_3/outbound/httpclient4/NamedThreadFactory.java b/02nio/nio02/src/main/java/io/github/tn/week03_3/outbound/httpclient4/NamedThreadFactory.java new file mode 100644 index 00000000..b395f6c1 --- /dev/null +++ b/02nio/nio02/src/main/java/io/github/tn/week03_3/outbound/httpclient4/NamedThreadFactory.java @@ -0,0 +1,32 @@ +package io.github.tn.week03_3.outbound.httpclient4; + +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.atomic.AtomicInteger; + +public class NamedThreadFactory implements ThreadFactory { + + private final ThreadGroup group; + private final AtomicInteger threadNumber = new AtomicInteger(1); + + private final String namePrefix; + private final boolean daemon; + + public NamedThreadFactory(String namePrefix, boolean daemon) { + this.daemon = daemon; + SecurityManager s = System.getSecurityManager(); + group = (s != null) ? s.getThreadGroup() : + Thread.currentThread().getThreadGroup(); + this.namePrefix = namePrefix; + } + + public NamedThreadFactory(String namePrefix) { + this(namePrefix, false); + } + + @Override + public Thread newThread(Runnable r) { + Thread t = new Thread(group, r, namePrefix + "-thread-" + threadNumber.getAndIncrement(), 0); + t.setDaemon(daemon); + return t; + } +} \ No newline at end of file diff --git a/02nio/nio02/src/main/java/io/github/tn/week03_3/outbound/netty4/NettyHttpClient.java b/02nio/nio02/src/main/java/io/github/tn/week03_3/outbound/netty4/NettyHttpClient.java new file mode 100644 index 00000000..27c0bbf4 --- /dev/null +++ b/02nio/nio02/src/main/java/io/github/tn/week03_3/outbound/netty4/NettyHttpClient.java @@ -0,0 +1,51 @@ +package io.github.tn.week03_3.outbound.netty4;//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 diff --git a/02nio/nio02/src/main/java/io/github/tn/week03_3/outbound/netty4/NettyHttpClientOutboundHandler.java b/02nio/nio02/src/main/java/io/github/tn/week03_3/outbound/netty4/NettyHttpClientOutboundHandler.java new file mode 100644 index 00000000..9f58f510 --- /dev/null +++ b/02nio/nio02/src/main/java/io/github/tn/week03_3/outbound/netty4/NettyHttpClientOutboundHandler.java @@ -0,0 +1,22 @@ +package io.github.tn.week03_3.outbound.netty4; + +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelInboundHandlerAdapter; + +public class NettyHttpClientOutboundHandler extends ChannelInboundHandlerAdapter { + + @Override + public void channelActive(ChannelHandlerContext ctx) + throws Exception { + + + } + + @Override + public void channelRead(ChannelHandlerContext ctx, Object msg) + throws Exception { + + + + } +} \ No newline at end of file diff --git a/02nio/nio02/src/main/java/io/github/tn/week03_3/outbound/okhttp/OkhttpOutboundHandler.java b/02nio/nio02/src/main/java/io/github/tn/week03_3/outbound/okhttp/OkhttpOutboundHandler.java new file mode 100644 index 00000000..16a65745 --- /dev/null +++ b/02nio/nio02/src/main/java/io/github/tn/week03_3/outbound/okhttp/OkhttpOutboundHandler.java @@ -0,0 +1,4 @@ +package io.github.tn.week03_3.outbound.okhttp; + +public class OkhttpOutboundHandler { +} diff --git a/02nio/nio02/src/main/java/io/github/tn/week03_3/router/HttpEndpointRouter.java b/02nio/nio02/src/main/java/io/github/tn/week03_3/router/HttpEndpointRouter.java new file mode 100644 index 00000000..62ceab38 --- /dev/null +++ b/02nio/nio02/src/main/java/io/github/tn/week03_3/router/HttpEndpointRouter.java @@ -0,0 +1,9 @@ +package io.github.tn.week03_3.router; + +import java.util.List; + +public interface HttpEndpointRouter { + + String route(List endpoints); + +} From 9b62a86271944959575b7cc25edb31b8f162b494 Mon Sep 17 00:00:00 2001 From: tn <1445763190@qq.com> Date: Sat, 7 Nov 2020 19:46:06 +0800 Subject: [PATCH 09/20] =?UTF-8?q?=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/main/java/java0/conc0303/tool/SemaphoreDemo.java | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/03concurrency/0301/src/main/java/java0/conc0303/tool/SemaphoreDemo.java b/03concurrency/0301/src/main/java/java0/conc0303/tool/SemaphoreDemo.java index f811c626..59472672 100644 --- a/03concurrency/0301/src/main/java/java0/conc0303/tool/SemaphoreDemo.java +++ b/03concurrency/0301/src/main/java/java0/conc0303/tool/SemaphoreDemo.java @@ -2,11 +2,15 @@ import java.util.concurrent.Semaphore; +/** + * 信号量 + */ public class SemaphoreDemo { public static void main(String[] args) { int N = 8; //工人数 - Semaphore semaphore = new Semaphore(5); //机器数目 + //如果设置为1就是串行了 + Semaphore semaphore = new Semaphore(1); //机器数目 for (int i = 0; i < N; i++) new Worker(i, semaphore).start(); } From cafe6ce75dc05e061a5eb118e535442f57c1b4cf Mon Sep 17 00:00:00 2001 From: tn <1445763190@qq.com> Date: Sat, 7 Nov 2020 19:51:37 +0800 Subject: [PATCH 10/20] =?UTF-8?q?=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/main/java/java0/conc0303/tool/CountDownLatchDemo2.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/03concurrency/0301/src/main/java/java0/conc0303/tool/CountDownLatchDemo2.java b/03concurrency/0301/src/main/java/java0/conc0303/tool/CountDownLatchDemo2.java index eff0ba40..7672d30b 100644 --- a/03concurrency/0301/src/main/java/java0/conc0303/tool/CountDownLatchDemo2.java +++ b/03concurrency/0301/src/main/java/java0/conc0303/tool/CountDownLatchDemo2.java @@ -23,12 +23,15 @@ public static void main(String[] args) throws Exception { } catch (Exception e) { e.printStackTrace(); } finally { + //确保contDown, test() 报错不影响其他 countDownLatch.countDown(); } }); } countDownLatch.await(); System.out.println("==>所有程序员完成任务,项目顺利上线!"); + // 关闭线程池中 当前使用的线程 + // 必须写,可能会阻塞线程池中的线程,造成线程一直等待工作 exec.shutdown(); } From 845cef382dcdbbb090fe8d30af7839517630fc04 Mon Sep 17 00:00:00 2001 From: tn <1445763190@qq.com> Date: Sat, 7 Nov 2020 19:56:53 +0800 Subject: [PATCH 11/20] =?UTF-8?q?=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/main/java/java0/conc0303/tool/CyclicBarrierDemo.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/03concurrency/0301/src/main/java/java0/conc0303/tool/CyclicBarrierDemo.java b/03concurrency/0301/src/main/java/java0/conc0303/tool/CyclicBarrierDemo.java index bc8417d7..dc4958c7 100644 --- a/03concurrency/0301/src/main/java/java0/conc0303/tool/CyclicBarrierDemo.java +++ b/03concurrency/0301/src/main/java/java0/conc0303/tool/CyclicBarrierDemo.java @@ -4,14 +4,14 @@ public class CyclicBarrierDemo { public static void main(String[] args) throws InterruptedException { - CyclicBarrier cyclicBarrier = new CyclicBarrier(5, new Runnable() { + CyclicBarrier cyclicBarrier = new CyclicBarrier(100, new Runnable() { @Override public void run() { System.out.println("回调>>"+Thread.currentThread().getName()); System.out.println("回调>>线程组执行结束"); } }); - for (int i = 0; i < 5; i++) { + for (int i = 0; i < 100; i++) { new Thread(new readNum(i,cyclicBarrier)).start(); } From 2f7fdaea942a29d37b340e3479ec46e91d1c9771 Mon Sep 17 00:00:00 2001 From: tn <1445763190@qq.com> Date: Sat, 7 Nov 2020 20:11:49 +0800 Subject: [PATCH 12/20] =?UTF-8?q?=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../conc0303/tool/CyclicBarrierDemo2.java | 80 ++++++++++++++++++- 1 file changed, 78 insertions(+), 2 deletions(-) diff --git a/03concurrency/0301/src/main/java/java0/conc0303/tool/CyclicBarrierDemo2.java b/03concurrency/0301/src/main/java/java0/conc0303/tool/CyclicBarrierDemo2.java index 9c83bc26..32d1d3c2 100644 --- a/03concurrency/0301/src/main/java/java0/conc0303/tool/CyclicBarrierDemo2.java +++ b/03concurrency/0301/src/main/java/java0/conc0303/tool/CyclicBarrierDemo2.java @@ -11,18 +11,94 @@ public static void main(String[] args) { for(int i=0;i Date: Sat, 7 Nov 2020 20:20:22 +0800 Subject: [PATCH 13/20] =?UTF-8?q?=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/main/java/java0/conc0303/future/FutureDemo1.java | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/03concurrency/0301/src/main/java/java0/conc0303/future/FutureDemo1.java b/03concurrency/0301/src/main/java/java0/conc0303/future/FutureDemo1.java index 14a16383..e3595353 100644 --- a/03concurrency/0301/src/main/java/java0/conc0303/future/FutureDemo1.java +++ b/03concurrency/0301/src/main/java/java0/conc0303/future/FutureDemo1.java @@ -8,10 +8,15 @@ public static void main(String[] args) { ExecutorService executor = Executors.newCachedThreadPool(); Future result = executor.submit(new Callable() { public Integer call() throws Exception { - return new Random().nextInt(); +// return new Random().nextInt(); + int numberInt = new Random().nextInt(); + System.out.println(numberInt); + return numberInt; + } }); executor.shutdown(); + // try 超时处理 try { System.out.println("result:" + result.get()); } catch (InterruptedException e) { From d7fea8df520e1e6446cc5e1030d057ed36d9fbba Mon Sep 17 00:00:00 2001 From: tn <1445763190@qq.com> Date: Sat, 7 Nov 2020 20:22:03 +0800 Subject: [PATCH 14/20] =?UTF-8?q?=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../0301/src/main/java/java0/conc0303/future/FutureDemo1.java | 1 + .../0301/src/main/java/java0/conc0303/future/FutureTask1.java | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/03concurrency/0301/src/main/java/java0/conc0303/future/FutureDemo1.java b/03concurrency/0301/src/main/java/java0/conc0303/future/FutureDemo1.java index e3595353..6945b4d8 100644 --- a/03concurrency/0301/src/main/java/java0/conc0303/future/FutureDemo1.java +++ b/03concurrency/0301/src/main/java/java0/conc0303/future/FutureDemo1.java @@ -3,6 +3,7 @@ import java.util.Random; import java.util.concurrent.*; +//方法回调 public class FutureDemo1 { public static void main(String[] args) { ExecutorService executor = Executors.newCachedThreadPool(); diff --git a/03concurrency/0301/src/main/java/java0/conc0303/future/FutureTask1.java b/03concurrency/0301/src/main/java/java0/conc0303/future/FutureTask1.java index 69499819..793c846d 100644 --- a/03concurrency/0301/src/main/java/java0/conc0303/future/FutureTask1.java +++ b/03concurrency/0301/src/main/java/java0/conc0303/future/FutureTask1.java @@ -2,7 +2,7 @@ import java.util.Random; import java.util.concurrent.*; - +//线程回调 public class FutureTask1 { public static void main(String[] args) { //第一种方式 From fd5302d31a3a2ce494c503b38fcda1f9a3c826f9 Mon Sep 17 00:00:00 2001 From: tn <1445763190@qq.com> Date: Sat, 7 Nov 2020 20:24:57 +0800 Subject: [PATCH 15/20] =?UTF-8?q?=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/java0/conc0303/future/CompletableFutureDemo.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/03concurrency/0301/src/main/java/java0/conc0303/future/CompletableFutureDemo.java b/03concurrency/0301/src/main/java/java0/conc0303/future/CompletableFutureDemo.java index 2a21f4f5..f5c7ae7e 100644 --- a/03concurrency/0301/src/main/java/java0/conc0303/future/CompletableFutureDemo.java +++ b/03concurrency/0301/src/main/java/java0/conc0303/future/CompletableFutureDemo.java @@ -6,12 +6,13 @@ public class CompletableFutureDemo { public static void main(String[] args){ - // 1.变换结果 + // 1.变换结果 - 返回结果 System.out.println("=====>1.变换结果"); + // lambada String result1 = CompletableFuture.supplyAsync(()->{return "Hello ";}).thenApplyAsync(v -> v + "world").join(); System.out.println(result1); - // 2.消费 + // 2.消费 - 不返回结果 内部直接答应结果 CompletableFuture.supplyAsync(()->{return "Hello ";}).thenAccept(v -> { System.out.println("=====>2.消费");System.out.println("consumer: " + v);}); // 3.组合 From 6a47d8903c6a71c35ef6181ec3a4f397f5fbcf43 Mon Sep 17 00:00:00 2001 From: tn <1445763190@qq.com> Date: Sat, 7 Nov 2020 20:34:06 +0800 Subject: [PATCH 16/20] =?UTF-8?q?=E3=80=82=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/java0/conc0303/future/CompletableFutureDemo.java | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/03concurrency/0301/src/main/java/java0/conc0303/future/CompletableFutureDemo.java b/03concurrency/0301/src/main/java/java0/conc0303/future/CompletableFutureDemo.java index f5c7ae7e..282d695e 100644 --- a/03concurrency/0301/src/main/java/java0/conc0303/future/CompletableFutureDemo.java +++ b/03concurrency/0301/src/main/java/java0/conc0303/future/CompletableFutureDemo.java @@ -17,14 +17,14 @@ public static void main(String[] args){ // 3.组合 System.out.println("=====>3.组合"); - String result3 = CompletableFuture.supplyAsync(()->{ + String result3 = CompletableFuture.supplyAsync(()->{//supplyAsync可以支持返回值 ,runAsync方法不支持返回值。 try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } return "Hello"; - }).thenCombine(CompletableFuture.supplyAsync(()->{ + }).thenCombine(CompletableFuture.supplyAsync(()->{// thenCombine合并任务 try { Thread.sleep(2000); } catch (InterruptedException e) { @@ -33,7 +33,9 @@ public static void main(String[] args){ return "world"; }),(s1,s2)->{return s1 + " " + s2;}).join(); System.out.println("thenCombine:"+result3); - + + // 当一个线程依赖另一个线程时,可以使用 thenApply 方法来把这两个线程串行化 + // thenAccept 消费处理结果 接收任务的处理结果,并消费处理,无返回结果。 CompletableFuture.supplyAsync(() -> "Hello, java course.") .thenApply(String::toUpperCase).thenCompose(s -> CompletableFuture.supplyAsync(s::toLowerCase)).thenAccept(v -> { System.out.println("thenCompose:"+v);}); From 6dfff841936edf02dc594fc7f9a941c60d5140bd Mon Sep 17 00:00:00 2001 From: tn <1445763190@qq.com> Date: Sat, 7 Nov 2020 23:20:45 +0800 Subject: [PATCH 17/20] =?UTF-8?q?=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../main/java/java0/conc0303/Homework03.java | 4 +- .../conc0303/stream/StreamParallelTest.java | 61 +++++++++++++++++++ 2 files changed, 63 insertions(+), 2 deletions(-) create mode 100644 03concurrency/0301/src/main/java/java0/conc0303/stream/StreamParallelTest.java diff --git a/03concurrency/0301/src/main/java/java0/conc0303/Homework03.java b/03concurrency/0301/src/main/java/java0/conc0303/Homework03.java index 3e64fc85..19ad470c 100644 --- a/03concurrency/0301/src/main/java/java0/conc0303/Homework03.java +++ b/03concurrency/0301/src/main/java/java0/conc0303/Homework03.java @@ -19,9 +19,9 @@ public static void main(String[] args) { // 确保 拿到result 并输出 System.out.println("异步计算结果为:"+result); - + System.out.println("使用时间:"+ (System.currentTimeMillis()-start) + " ms"); - + // 然后退出main线程 } diff --git a/03concurrency/0301/src/main/java/java0/conc0303/stream/StreamParallelTest.java b/03concurrency/0301/src/main/java/java0/conc0303/stream/StreamParallelTest.java new file mode 100644 index 00000000..c5c6c48e --- /dev/null +++ b/03concurrency/0301/src/main/java/java0/conc0303/stream/StreamParallelTest.java @@ -0,0 +1,61 @@ +package java0.conc0303.stream; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +/** + * parallel 不适合IO密集型 (多线程处理) + * @author tn + * @version 1 + * @ClassName StreamParallelTest + * @description + * @date 2020/11/7 22:24 + */ +public class StreamParallelTest { + + public static void main(String[] args) { + List list = new ArrayList<>(); + BlockingQueue blockingQueue = new LinkedBlockingQueue(10000); + //随机设置值 + IntStream.range(1, 10000).forEach(i -> list.add(i)); + System.out.println("Integer:"+list.toString()); + + +// List longList = list.stream().parallel() +// .map(i -> i.longValue()) +// .sorted() +// .collect(Collectors.toList()); + List longList = list.stream().map(i -> i.longValue()).sorted().collect(Collectors.toList()); + long start=System.currentTimeMillis(); + +// 并行,默认使用CPU * 2个线程 +// longList.stream().parallel().forEach( +// i -> { +// try { +// blockingQueue.put(i); +// } catch (InterruptedException e) { +// e.printStackTrace(); +// } +// }); + longList.stream().forEach( + i -> { + try { + blockingQueue.put(i); + } catch (InterruptedException e) { + e.printStackTrace(); + } + }); + System.out.println("blockingQueue:" + blockingQueue.toString()); + + System.out.println("使用时间:"+ (System.currentTimeMillis()-start) + " ms"); + + System.out.println("longList:"+longList.toString()); + +// BlockingQueue blockingQueue = new LinkedBlockingQueue(10000); + } + +} From 33dda2d430627bfb0eda105d6140ce7bd6bf7b5b Mon Sep 17 00:00:00 2001 From: tn <1445763190@qq.com> Date: Thu, 12 Nov 2020 21:16:09 +0800 Subject: [PATCH 18/20] =?UTF-8?q?=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../main/java/java0/nio01/HttpClinet01.java | 29 +++++++++++++++++++ test/MainTest.java | 27 +++++++++++++++++ 2 files changed, 56 insertions(+) create mode 100644 02nio/nio01/src/main/java/java0/nio01/HttpClinet01.java create mode 100644 test/MainTest.java diff --git a/02nio/nio01/src/main/java/java0/nio01/HttpClinet01.java b/02nio/nio01/src/main/java/java0/nio01/HttpClinet01.java new file mode 100644 index 00000000..1c4c2473 --- /dev/null +++ b/02nio/nio01/src/main/java/java0/nio01/HttpClinet01.java @@ -0,0 +1,29 @@ +package java0.nio01; + +import java.io.IOException; +import java.io.InputStream; +import java.net.Socket; + +public class HttpClinet01 { + public static void main(String[] args) throws IOException{ + Socket clientSocket = new Socket("127.0.0.1",8801); + client(clientSocket); + } + + private static void client(Socket socket) { + try { + // 获取服务端消息 + InputStream socketData = socket.getInputStream(); + //读取流数据 (socket返回的数据) + byte[] buf = new byte[1024]; + int len = 0; + while ((len = socketData.read(buf)) != -1) { + System.out.println(new String(buf, 0, len)); + } + socket.close(); + } catch (IOException e) { + e.printStackTrace(); + } + + } +} \ No newline at end of file diff --git a/test/MainTest.java b/test/MainTest.java new file mode 100644 index 00000000..4bc4088d --- /dev/null +++ b/test/MainTest.java @@ -0,0 +1,27 @@ +import org.apache.commons.codec.digest.DigestUtils; + +/** + * @author tn + * @version 1 + * @ClassName MainTest + * @description + * @date 2020/11/8 15:13 + */ +public class MainTest { + public static void main(String[] args) { + String hash=""; + String txt ="39"; + + // MD2 + for(int i=0;i<200000000;i++){ + /// public static byte[] md2(String data) { + // return md2(StringUtils.getBytesUtf8(data)); + // } + hash = DigestUtils.md2Hex(txt); + } + + System.out.println(hash); + + } + +} From 1fd9dfb7ccf559f62ee09327e4f3953267022f46 Mon Sep 17 00:00:00 2001 From: tn <1445763190@qq.com> Date: Thu, 12 Nov 2020 21:31:15 +0800 Subject: [PATCH 19/20] =?UTF-8?q?=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../main/java/io/kimmking/spring01/GuavaDemo.java | 12 +----------- .../main/java/io/kimmking/spring01/StreamDemo.java | 6 +----- .../src/main/java/io/kimmking/spring02/Aop2.java | 6 +----- .../main/java/io/kimmking/springjms/JmsReceiver.java | 1 - 04fx/spring01/src/test/java/Spring02Test.java | 1 + 5 files changed, 4 insertions(+), 22 deletions(-) diff --git a/04fx/spring01/src/main/java/io/kimmking/spring01/GuavaDemo.java b/04fx/spring01/src/main/java/io/kimmking/spring01/GuavaDemo.java index 98ef1c51..312ccaa2 100644 --- a/04fx/spring01/src/main/java/io/kimmking/spring01/GuavaDemo.java +++ b/04fx/spring01/src/main/java/io/kimmking/spring01/GuavaDemo.java @@ -3,12 +3,7 @@ import com.alibaba.fastjson.JSON; import com.google.common.base.Joiner; import com.google.common.base.Splitter; -import com.google.common.collect.ArrayListMultimap; -import com.google.common.collect.BiMap; -import com.google.common.collect.HashBiMap; -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import com.google.common.collect.Multimap; +import com.google.common.collect.*; import com.google.common.eventbus.EventBus; import com.google.common.eventbus.Subscribe; import lombok.AllArgsConstructor; @@ -16,13 +11,8 @@ import lombok.SneakyThrows; import java.io.IOException; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.Optional; -import java.util.stream.Collectors; public class GuavaDemo { diff --git a/04fx/spring01/src/main/java/io/kimmking/spring01/StreamDemo.java b/04fx/spring01/src/main/java/io/kimmking/spring01/StreamDemo.java index 835e1f21..5f431204 100644 --- a/04fx/spring01/src/main/java/io/kimmking/spring01/StreamDemo.java +++ b/04fx/spring01/src/main/java/io/kimmking/spring01/StreamDemo.java @@ -3,11 +3,7 @@ import com.alibaba.fastjson.JSON; import java.io.IOException; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; +import java.util.*; import java.util.stream.Collectors; public class StreamDemo { diff --git a/04fx/spring01/src/main/java/io/kimmking/spring02/Aop2.java b/04fx/spring01/src/main/java/io/kimmking/spring02/Aop2.java index b8eae255..df45a80c 100644 --- a/04fx/spring01/src/main/java/io/kimmking/spring02/Aop2.java +++ b/04fx/spring01/src/main/java/io/kimmking/spring02/Aop2.java @@ -2,11 +2,7 @@ import org.aspectj.lang.ProceedingJoinPoint; -import org.aspectj.lang.annotation.AfterReturning; -import org.aspectj.lang.annotation.Around; -import org.aspectj.lang.annotation.Aspect; -import org.aspectj.lang.annotation.Before; -import org.aspectj.lang.annotation.Pointcut; +import org.aspectj.lang.annotation.*; @Aspect public class Aop2 { diff --git a/04fx/spring01/src/main/java/io/kimmking/springjms/JmsReceiver.java b/04fx/spring01/src/main/java/io/kimmking/springjms/JmsReceiver.java index 1373b66f..ee085020 100644 --- a/04fx/spring01/src/main/java/io/kimmking/springjms/JmsReceiver.java +++ b/04fx/spring01/src/main/java/io/kimmking/springjms/JmsReceiver.java @@ -1,6 +1,5 @@ package io.kimmking.springjms; -import io.kimmking.spring01.Student; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; diff --git a/04fx/spring01/src/test/java/Spring02Test.java b/04fx/spring01/src/test/java/Spring02Test.java index 2cacae2e..73013dec 100644 --- a/04fx/spring01/src/test/java/Spring02Test.java +++ b/04fx/spring01/src/test/java/Spring02Test.java @@ -1,6 +1,7 @@ import io.kimmking.spring02.Klass; import org.junit.Assert; import org.junit.Test; + import static org.mockito.Mockito.*; public class Spring02Test { From 54d5ee8c3ae9822656aacf9cfcc93a06ac85d2b7 Mon Sep 17 00:00:00 2001 From: tn <1445763190@qq.com> Date: Thu, 12 Nov 2020 21:31:21 +0800 Subject: [PATCH 20/20] =?UTF-8?q?=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- 04fx/spring01/src/main/java/io/kimmking/spring01/StreamDemo.java | 1 - 1 file changed, 1 deletion(-) diff --git a/04fx/spring01/src/main/java/io/kimmking/spring01/StreamDemo.java b/04fx/spring01/src/main/java/io/kimmking/spring01/StreamDemo.java index 5f431204..97ef69f5 100644 --- a/04fx/spring01/src/main/java/io/kimmking/spring01/StreamDemo.java +++ b/04fx/spring01/src/main/java/io/kimmking/spring01/StreamDemo.java @@ -3,7 +3,6 @@ import com.alibaba.fastjson.JSON; import java.io.IOException; -import java.util.*; import java.util.stream.Collectors; public class StreamDemo {