From 287f6205f3183654712da44d85c9fdc1bc5b4c91 Mon Sep 17 00:00:00 2001 From: penghuiliu <11090829@qq.com> Date: Sun, 1 Nov 2020 22:30:51 +0800 Subject: [PATCH 1/6] =?UTF-8?q?=E5=9F=BA=E4=BA=8ENetty=E5=AE=9E=E7=8E=B0?= =?UTF-8?q?=E7=BD=91=E5=85=B3HttpClient?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- 02nio/nio02/pom.xml | 8 ++ .../gateway/inbound/HttpInboundHandler.java | 14 ++- .../outbound/netty4/NettyHttpClient.java | 107 +++++++++--------- .../NettyHttpClientOutboundHandler.java | 83 +++++++++++--- .../java/java0/conc0301/sync/Counter.java | 8 +- 5 files changed, 150 insertions(+), 70 deletions(-) diff --git a/02nio/nio02/pom.xml b/02nio/nio02/pom.xml index 6cbbeffd..6140ac78 100644 --- a/02nio/nio02/pom.xml +++ b/02nio/nio02/pom.xml @@ -47,6 +47,14 @@ slf4j-log4j12 1.7.25 + + + com.squareup.okhttp3 + okhttp + 3.11.0 + + + org.apache.httpcomponents httpasyncclient 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..0ec638ab 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,6 +1,8 @@ package io.github.kimmking.gateway.inbound; import io.github.kimmking.gateway.outbound.httpclient4.HttpOutboundHandler; +import io.github.kimmking.gateway.outbound.netty4.NettyHttpClient; +import io.github.kimmking.gateway.outbound.okhttp.OkhttpOutboundHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.handler.codec.http.FullHttpRequest; @@ -13,10 +15,15 @@ public class HttpInboundHandler extends ChannelInboundHandlerAdapter { private static Logger logger = LoggerFactory.getLogger(HttpInboundHandler.class); private final String proxyServer; private HttpOutboundHandler handler; + + private NettyHttpClient nettyHandler; + + private OkhttpOutboundHandler okhttpOutboundHandler; public HttpInboundHandler(String proxyServer) { this.proxyServer = proxyServer; handler = new HttpOutboundHandler(this.proxyServer); + nettyHandler = new NettyHttpClient("127.0.0.1", 8089); } @Override @@ -34,8 +41,9 @@ public void channelRead(ChannelHandlerContext ctx, Object msg) { // if (uri.contains("/test")) { // handlerTest(fullRequest, ctx); // } - - handler.handle(fullRequest, ctx); + + //handler.handle(fullRequest, ctx); + nettyHandler.handle(fullRequest, ctx); } catch(Exception e) { e.printStackTrace(); @@ -44,6 +52,8 @@ public void channelRead(ChannelHandlerContext ctx, Object msg) { } } + + // private void handlerTest(FullHttpRequest fullRequest, ChannelHandlerContext ctx) { // FullHttpResponse response = null; // try { 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..289ec362 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,56 @@ -//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.nio.NioSocketChannel; +import io.netty.handler.codec.http.*; + +import java.net.URI; + +public class NettyHttpClient { + + private String host; + + private int port; + + public NettyHttpClient(String host, int port) { + this.host = host; + this.port = port; + } + + public void handle(final FullHttpRequest fullRequest, final ChannelHandlerContext ctx) throws Exception { + EventLoopGroup workerGroup = new NioEventLoopGroup(); + + try { + Bootstrap b = new Bootstrap(); + b.group(workerGroup); + //b.remoteAddress(host, port); + b.channel(NioSocketChannel.class); + b.option(ChannelOption.SO_KEEPALIVE, true); + b.handler(new ChannelInitializer() { + @Override + public void initChannel(Channel ch) throws Exception { + //包含编码器和解码器 + ch.pipeline().addLast(new HttpClientCodec()); + //聚合 + ch.pipeline().addLast(new HttpObjectAggregator(1024 * 10 * 1024)); + //解压 + ch.pipeline().addLast(new HttpContentDecompressor()); + // 客户端接收到的是httpResponse响应,所以要使用HttpResponseDecoder进行解码 + // 客户端接收到的是httpResponse响应,所以要使用HttpResponseDecoder进行解码 + // ch.pipeline().addLast(new HttpResponseDecoder()); + // 客户端发送的是httprequest,所以要使用HttpRequestEncoder进行编码 + // ch.pipeline().addLast(new HttpRequestEncoder()); + ch.pipeline().addLast(new NettyHttpClientOutboundHandler(ctx, fullRequest)); + } + }); + + // Start the client. + ChannelFuture f = b.connect(host, port).sync(); + f.channel().closeFuture().sync(); + } finally { + workerGroup.shutdownGracefully(); + } + } +} \ 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..df1c3291 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,22 +1,77 @@ package io.github.kimmking.gateway.outbound.netty4; -import io.netty.channel.ChannelHandlerContext; -import io.netty.channel.ChannelInboundHandlerAdapter; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import io.netty.channel.*; +import io.netty.handler.codec.http.*; +import io.netty.util.CharsetUtil; +import org.apache.http.util.EntityUtils; + +import java.net.URI; + +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 ChannelHandlerContext ctx1; + + private FullHttpRequest fullRequest; + + public NettyHttpClientOutboundHandler(ChannelHandlerContext ctx1, FullHttpRequest fullRequest) { + this.ctx1 = ctx1; + this.fullRequest = fullRequest; + } + + /** + * 读取数据 + * @param ctx + * @param msg + * @throws Exception + */ + @Override + public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { + FullHttpResponse response = null; + try { + if (msg instanceof FullHttpResponse) { + System.out.println(111111); + FullHttpResponse response1 = (FullHttpResponse)msg; + ByteBuf buf = response1.content(); + String result = buf.toString(CharsetUtil.UTF_8); + System.out.println("response -> "+result); + response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(result.getBytes("UTF-8"))); + response.headers().set("Content-Type", "application/json"); + response.headers().setInt("Content-Length", Integer.parseInt("65535")); + + } + } catch (Exception e) { + e.printStackTrace(); + } finally { + if (fullRequest != null) { + if (!HttpUtil.isKeepAlive(fullRequest)) { + ctx1.write(response).addListener(ChannelFutureListener.CLOSE); + } else { + ctx1.write(response); + } + } + ctx1.flush(); + } + } -public class NettyHttpClientOutboundHandler extends ChannelInboundHandlerAdapter { - @Override - public void channelActive(ChannelHandlerContext ctx) - throws Exception { - - + public void channelActive(ChannelHandlerContext ctx) throws Exception { + URI uri = new URI("http://127.0.0.1:8089/api/hello1"); + String msg = "Are you ok?"; + DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_0, HttpMethod.GET, uri.toASCIIString()); + // 构建http请求 + request.headers().add(HttpHeaderNames.CONNECTION,HttpHeaderValues.KEEP_ALIVE); + request.headers().add(HttpHeaderNames.CONTENT_LENGTH,request.content().readableBytes()); + ctx.writeAndFlush(request); } - + @Override - public void channelRead(ChannelHandlerContext ctx, Object msg) - throws Exception { - - - + public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { + ctx.flush(); + super.exceptionCaught(ctx, cause); } } \ No newline at end of file diff --git a/03concurrency/0301/src/main/java/java0/conc0301/sync/Counter.java b/03concurrency/0301/src/main/java/java0/conc0301/sync/Counter.java index a066caf8..8b124fc0 100644 --- a/03concurrency/0301/src/main/java/java0/conc0301/sync/Counter.java +++ b/03concurrency/0301/src/main/java/java0/conc0301/sync/Counter.java @@ -1,12 +1,14 @@ package java0.conc0301.sync; +import java.util.concurrent.atomic.AtomicInteger; + public class Counter { - private int sum = 0; + private AtomicInteger sum = new AtomicInteger(0); public void incr() { - sum++; + sum.addAndGet(1); } public int getSum() { - return sum; + return sum.intValue(); } public static void main(String[] args) throws InterruptedException { From 54004ba77cce3c93eca3f72328c32f3484a5a2b7 Mon Sep 17 00:00:00 2001 From: Redick01 <11090829@qq.com> Date: Mon, 2 Nov 2020 14:08:55 +0800 Subject: [PATCH 2/6] =?UTF-8?q?=E8=A7=A3=E5=86=B3=E5=AE=A2=E6=88=B7?= =?UTF-8?q?=E7=AB=AF=E8=AF=B7=E6=B1=82=E4=B8=80=E7=9B=B4loading=E9=97=AE?= =?UTF-8?q?=E9=A2=98=EF=BC=8C=E5=8E=BB=E6=8E=89request=E7=9A=84keepalive?= =?UTF-8?q?=E5=8D=B3=E5=8F=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../gateway/inbound/HttpInboundHandler.java | 2 +- .../NettyHttpClientOutboundHandler.java | 28 ++++++++++--------- 2 files changed, 16 insertions(+), 14 deletions(-) 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 0ec638ab..f297d8d5 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 @@ -23,7 +23,7 @@ public class HttpInboundHandler extends ChannelInboundHandlerAdapter { public HttpInboundHandler(String proxyServer) { this.proxyServer = proxyServer; handler = new HttpOutboundHandler(this.proxyServer); - nettyHandler = new NettyHttpClient("127.0.0.1", 8089); + nettyHandler = new NettyHttpClient("127.0.0.1", 8088); } @Override 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 df1c3291..bba85376 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 @@ -32,39 +32,41 @@ public NettyHttpClientOutboundHandler(ChannelHandlerContext ctx1, FullHttpReques @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { FullHttpResponse response = null; + DefaultFullHttpResponse defaultFullHttpResponse = null; try { if (msg instanceof FullHttpResponse) { System.out.println(111111); - FullHttpResponse response1 = (FullHttpResponse)msg; - ByteBuf buf = response1.content(); + response = (FullHttpResponse) msg; + ByteBuf buf = response.content(); String result = buf.toString(CharsetUtil.UTF_8); System.out.println("response -> "+result); - response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(result.getBytes("UTF-8"))); - response.headers().set("Content-Type", "application/json"); - response.headers().setInt("Content-Length", Integer.parseInt("65535")); - + defaultFullHttpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_0, response.status(), Unpooled.wrappedBuffer(result.getBytes("UTF-8"))); + defaultFullHttpResponse.headers().add(HttpHeaderNames.CONTENT_TYPE, "application/json"); + defaultFullHttpResponse.headers().add(HttpHeaderNames.CONNECTION,HttpHeaderValues.KEEP_ALIVE); + defaultFullHttpResponse.headers().add(HttpHeaderNames.CONTENT_LENGTH, buf.readableBytes()); } - } catch (Exception e) { - e.printStackTrace(); - } finally { if (fullRequest != null) { if (!HttpUtil.isKeepAlive(fullRequest)) { - ctx1.write(response).addListener(ChannelFutureListener.CLOSE); + ctx1.write(defaultFullHttpResponse).addListener(ChannelFutureListener.CLOSE); } else { - ctx1.write(response); + ctx1.write(defaultFullHttpResponse); } } + } catch (Exception e) { + e.printStackTrace(); + } finally { ctx1.flush(); + } } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { - URI uri = new URI("http://127.0.0.1:8089/api/hello1"); + URI uri = new URI("http://127.0.0.1:8088/api/hello"); String msg = "Are you ok?"; DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_0, HttpMethod.GET, uri.toASCIIString()); // 构建http请求 - request.headers().add(HttpHeaderNames.CONNECTION,HttpHeaderValues.KEEP_ALIVE); + // request.headers().add(HttpHeaderNames.CONNECTION,HttpHeaderValues.CLOSE); request.headers().add(HttpHeaderNames.CONTENT_LENGTH,request.content().readableBytes()); ctx.writeAndFlush(request); } From 5c9d2f1e0a4f1f126eebfd7efa906c85d4694e90 Mon Sep 17 00:00:00 2001 From: Redick01 <11090829@qq.com> Date: Tue, 3 Nov 2020 21:17:33 +0800 Subject: [PATCH 3/6] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E8=BF=87=E6=BB=A4?= =?UTF-8?q?=E5=99=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../gateway/filter/HttpRequestFilter.java | 1 - .../impl/HttpRequestHeadFilterImpl.java | 20 +++++++++++ .../gateway/inbound/HttpInboundHandler.java | 8 ++++- .../outbound/netty4/NettyHttpClient.java | 12 +++---- .../NettyHttpClientOutboundHandler.java | 35 +++++++++++++------ 5 files changed, 55 insertions(+), 21 deletions(-) create mode 100644 02nio/nio02/src/main/java/io/github/kimmking/gateway/filter/impl/HttpRequestHeadFilterImpl.java diff --git a/02nio/nio02/src/main/java/io/github/kimmking/gateway/filter/HttpRequestFilter.java b/02nio/nio02/src/main/java/io/github/kimmking/gateway/filter/HttpRequestFilter.java index 31253b40..61c1e597 100644 --- a/02nio/nio02/src/main/java/io/github/kimmking/gateway/filter/HttpRequestFilter.java +++ b/02nio/nio02/src/main/java/io/github/kimmking/gateway/filter/HttpRequestFilter.java @@ -6,5 +6,4 @@ public interface HttpRequestFilter { void filter(FullHttpRequest fullRequest, ChannelHandlerContext ctx); - } diff --git a/02nio/nio02/src/main/java/io/github/kimmking/gateway/filter/impl/HttpRequestHeadFilterImpl.java b/02nio/nio02/src/main/java/io/github/kimmking/gateway/filter/impl/HttpRequestHeadFilterImpl.java new file mode 100644 index 00000000..fae1eb0a --- /dev/null +++ b/02nio/nio02/src/main/java/io/github/kimmking/gateway/filter/impl/HttpRequestHeadFilterImpl.java @@ -0,0 +1,20 @@ +package io.github.kimmking.gateway.filter.impl; + +import io.github.kimmking.gateway.filter.HttpRequestFilter; +import io.netty.channel.ChannelHandlerContext; +import io.netty.handler.codec.http.FullHttpRequest; +import io.netty.handler.codec.http.HttpHeaderNames; +import io.netty.handler.codec.http.HttpHeaderValues; + +/** + * @author liu_penghui + * @date 2020/11/3. + */ +public class HttpRequestHeadFilterImpl implements HttpRequestFilter { + + @Override + public void filter(FullHttpRequest fullRequest, ChannelHandlerContext ctx) { + fullRequest.headers().set("nio", "liupenghui"); + fullRequest.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE); + } +} 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 f297d8d5..46a73f68 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,5 +1,7 @@ package io.github.kimmking.gateway.inbound; +import io.github.kimmking.gateway.filter.HttpRequestFilter; +import io.github.kimmking.gateway.filter.impl.HttpRequestHeadFilterImpl; import io.github.kimmking.gateway.outbound.httpclient4.HttpOutboundHandler; import io.github.kimmking.gateway.outbound.netty4.NettyHttpClient; import io.github.kimmking.gateway.outbound.okhttp.OkhttpOutboundHandler; @@ -19,11 +21,14 @@ public class HttpInboundHandler extends ChannelInboundHandlerAdapter { private NettyHttpClient nettyHandler; private OkhttpOutboundHandler okhttpOutboundHandler; + + private HttpRequestFilter filter; public HttpInboundHandler(String proxyServer) { this.proxyServer = proxyServer; handler = new HttpOutboundHandler(this.proxyServer); nettyHandler = new NettyHttpClient("127.0.0.1", 8088); + filter = new HttpRequestHeadFilterImpl(); } @Override @@ -43,7 +48,8 @@ public void channelRead(ChannelHandlerContext ctx, Object msg) { // } //handler.handle(fullRequest, ctx); - nettyHandler.handle(fullRequest, ctx); + filter.filter(fullRequest, ctx); + nettyHandler.handle(fullRequest, ctx, proxyServer); } catch(Exception e) { e.printStackTrace(); 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 289ec362..5bdb5df6 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 @@ -6,8 +6,6 @@ import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.codec.http.*; -import java.net.URI; - public class NettyHttpClient { private String host; @@ -19,9 +17,8 @@ public NettyHttpClient(String host, int port) { this.port = port; } - public void handle(final FullHttpRequest fullRequest, final ChannelHandlerContext ctx) throws Exception { - EventLoopGroup workerGroup = new NioEventLoopGroup(); - + public void handle(final FullHttpRequest fullRequest, final ChannelHandlerContext ctx, String proxyServer) throws Exception { + EventLoopGroup workerGroup = new NioEventLoopGroup(16); try { Bootstrap b = new Bootstrap(); b.group(workerGroup); @@ -34,7 +31,7 @@ public void initChannel(Channel ch) throws Exception { //包含编码器和解码器 ch.pipeline().addLast(new HttpClientCodec()); //聚合 - ch.pipeline().addLast(new HttpObjectAggregator(1024 * 10 * 1024)); + ch.pipeline().addLast(new HttpObjectAggregator(512 * 1024)); //解压 ch.pipeline().addLast(new HttpContentDecompressor()); // 客户端接收到的是httpResponse响应,所以要使用HttpResponseDecoder进行解码 @@ -42,10 +39,9 @@ public void initChannel(Channel ch) throws Exception { // ch.pipeline().addLast(new HttpResponseDecoder()); // 客户端发送的是httprequest,所以要使用HttpRequestEncoder进行编码 // ch.pipeline().addLast(new HttpRequestEncoder()); - ch.pipeline().addLast(new NettyHttpClientOutboundHandler(ctx, fullRequest)); + ch.pipeline().addLast(new NettyHttpClientOutboundHandler(ctx, fullRequest, proxyServer)); } }); - // Start the client. ChannelFuture f = b.connect(host, port).sync(); f.channel().closeFuture().sync(); 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 bba85376..8cdd2ee2 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 @@ -8,8 +8,11 @@ import org.apache.http.util.EntityUtils; import java.net.URI; +import java.util.List; +import java.util.Map; import static io.netty.handler.codec.http.HttpResponseStatus.OK; +import static io.netty.handler.codec.http.HttpVersion.HTTP_1_0; import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1; public class NettyHttpClientOutboundHandler extends ChannelInboundHandlerAdapter { @@ -18,9 +21,12 @@ public class NettyHttpClientOutboundHandler extends ChannelInboundHandlerAdapter private FullHttpRequest fullRequest; - public NettyHttpClientOutboundHandler(ChannelHandlerContext ctx1, FullHttpRequest fullRequest) { + private String backUrl; + + public NettyHttpClientOutboundHandler(ChannelHandlerContext ctx1, FullHttpRequest fullRequest, String url) { this.ctx1 = ctx1; this.fullRequest = fullRequest; + this.backUrl = url.endsWith("/") ? url.substring(0, url.length() - 1) : url; } /** @@ -35,14 +41,12 @@ public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception DefaultFullHttpResponse defaultFullHttpResponse = null; try { if (msg instanceof FullHttpResponse) { - System.out.println(111111); response = (FullHttpResponse) msg; ByteBuf buf = response.content(); String result = buf.toString(CharsetUtil.UTF_8); - System.out.println("response -> "+result); defaultFullHttpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_0, response.status(), Unpooled.wrappedBuffer(result.getBytes("UTF-8"))); defaultFullHttpResponse.headers().add(HttpHeaderNames.CONTENT_TYPE, "application/json"); - defaultFullHttpResponse.headers().add(HttpHeaderNames.CONNECTION,HttpHeaderValues.KEEP_ALIVE); + defaultFullHttpResponse.headers().add(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE); defaultFullHttpResponse.headers().add(HttpHeaderNames.CONTENT_LENGTH, buf.readableBytes()); } if (fullRequest != null) { @@ -62,13 +66,22 @@ public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { - URI uri = new URI("http://127.0.0.1:8088/api/hello"); - String msg = "Are you ok?"; - DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_0, HttpMethod.GET, uri.toASCIIString()); - // 构建http请求 - // request.headers().add(HttpHeaderNames.CONNECTION,HttpHeaderValues.CLOSE); - request.headers().add(HttpHeaderNames.CONTENT_LENGTH,request.content().readableBytes()); - ctx.writeAndFlush(request); + try { + URI uri = new URI(backUrl + fullRequest.uri()); + // 获取Netty内置的请求头对象 + HttpHeaders header = fullRequest.headers(); + // 将包含的请求信息赋值到list中 + List> list = header.entries(); + DefaultFullHttpRequest request = new DefaultFullHttpRequest(HTTP_1_0, HttpMethod.GET, uri.toASCIIString()); + for (Map.Entry map : list) { + request.headers().add(map.getKey(), map.getValue()); + } + request.setProtocolVersion(HTTP_1_0); + ctx.writeAndFlush(request); + } catch (Exception e) { + e.printStackTrace(); + ctx.flush(); + } } @Override From 48dcae928e10445d7bc0d496564451f8da21648d Mon Sep 17 00:00:00 2001 From: Redick01 <11090829@qq.com> Date: Wed, 4 Nov 2020 19:37:26 +0800 Subject: [PATCH 4/6] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E8=BF=87=E6=BB=A4?= =?UTF-8?q?=E5=99=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../kimmking/gateway/outbound/netty4/NettyHttpClient.java | 5 +++-- .../outbound/netty4/NettyHttpClientOutboundHandler.java | 6 ++---- 2 files changed, 5 insertions(+), 6 deletions(-) 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 5bdb5df6..b2ad6119 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 @@ -3,6 +3,7 @@ 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.*; @@ -25,9 +26,9 @@ public void handle(final FullHttpRequest fullRequest, final ChannelHandlerContex //b.remoteAddress(host, port); b.channel(NioSocketChannel.class); b.option(ChannelOption.SO_KEEPALIVE, true); - b.handler(new ChannelInitializer() { + b.handler(new ChannelInitializer() { @Override - public void initChannel(Channel ch) throws Exception { + public void initChannel(SocketChannel ch) throws Exception { //包含编码器和解码器 ch.pipeline().addLast(new HttpClientCodec()); //聚合 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 8cdd2ee2..69586ebf 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 @@ -44,8 +44,7 @@ public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception response = (FullHttpResponse) msg; ByteBuf buf = response.content(); String result = buf.toString(CharsetUtil.UTF_8); - defaultFullHttpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_0, response.status(), Unpooled.wrappedBuffer(result.getBytes("UTF-8"))); - defaultFullHttpResponse.headers().add(HttpHeaderNames.CONTENT_TYPE, "application/json"); + defaultFullHttpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, response.status(), Unpooled.wrappedBuffer(result.getBytes("UTF-8"))); defaultFullHttpResponse.headers().add(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE); defaultFullHttpResponse.headers().add(HttpHeaderNames.CONTENT_LENGTH, buf.readableBytes()); } @@ -72,11 +71,10 @@ public void channelActive(ChannelHandlerContext ctx) throws Exception { HttpHeaders header = fullRequest.headers(); // 将包含的请求信息赋值到list中 List> list = header.entries(); - DefaultFullHttpRequest request = new DefaultFullHttpRequest(HTTP_1_0, HttpMethod.GET, uri.toASCIIString()); + DefaultFullHttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, HttpMethod.GET, uri.toASCIIString()); for (Map.Entry map : list) { request.headers().add(map.getKey(), map.getValue()); } - request.setProtocolVersion(HTTP_1_0); ctx.writeAndFlush(request); } catch (Exception e) { e.printStackTrace(); From e5c3a6e1cd0427dd966fe1aa2c58666e25444733 Mon Sep 17 00:00:00 2001 From: penghuiliu <11090829@qq.com> Date: Wed, 4 Nov 2020 23:40:41 +0800 Subject: [PATCH 5/6] =?UTF-8?q?=E6=B7=BB=E5=8A=A0ribbon=E4=BE=9D=E8=B5=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- 02nio/nio02/pom.xml | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/02nio/nio02/pom.xml b/02nio/nio02/pom.xml index 6140ac78..91d78573 100644 --- a/02nio/nio02/pom.xml +++ b/02nio/nio02/pom.xml @@ -60,7 +60,19 @@ httpasyncclient 4.1.4 - + + com.netflix.ribbon + ribbon + 2.7.17 + + + + org.springframework.cloud + spring-cloud-starter-ribbon + 1.3.0.RELEASE + + +