From ac4748d423ab4745259a6b856f431c3a3b705cd4 Mon Sep 17 00:00:00 2001 From: hiram <1104712460@qq.com> Date: Fri, 30 Oct 2020 17:01:26 +0800 Subject: [PATCH 1/7] gateway1.0 --- .../gateway/NettyServerApplication.java | 2 +- .../gateway/inbound/HttpInboundHandler.java | 13 ++- .../gateway/inbound/HttpInboundServer.java | 2 + .../outbound/netty4/NettyHttpClient.java | 106 +++++++++--------- .../NettyHttpClientOutboundHandler.java | 22 ---- .../netty4/NettyHttpOutboundHandler.java | 86 ++++++++++++++ .../kimmking/gateway/util/ByteBufToBytes.java | 37 ++++++ 7 files changed, 190 insertions(+), 78 deletions(-) delete mode 100644 02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/netty4/NettyHttpClientOutboundHandler.java create mode 100644 02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/netty4/NettyHttpOutboundHandler.java create mode 100644 02nio/nio02/src/main/java/io/github/kimmking/gateway/util/ByteBufToBytes.java diff --git a/02nio/nio02/src/main/java/io/github/kimmking/gateway/NettyServerApplication.java b/02nio/nio02/src/main/java/io/github/kimmking/gateway/NettyServerApplication.java index 870b2d4f..c539b5ec 100644 --- a/02nio/nio02/src/main/java/io/github/kimmking/gateway/NettyServerApplication.java +++ b/02nio/nio02/src/main/java/io/github/kimmking/gateway/NettyServerApplication.java @@ -21,7 +21,7 @@ public static void main(String[] args) { System.out.println(GATEWAY_NAME + " " + GATEWAY_VERSION +" started at http://localhost:" + port + " for server:" + proxyServer); try { server.run(); - }catch (Exception ex){ + } catch (Exception ex){ ex.printStackTrace(); } } 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..58a74fa5 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.netty4.NettyHttpOutboundHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.handler.codec.http.FullHttpRequest; @@ -12,11 +14,11 @@ public class HttpInboundHandler extends ChannelInboundHandlerAdapter { private static Logger logger = LoggerFactory.getLogger(HttpInboundHandler.class); private final String proxyServer; - private HttpOutboundHandler handler; + private NettyHttpClient handler; public HttpInboundHandler(String proxyServer) { this.proxyServer = proxyServer; - handler = new HttpOutboundHandler(this.proxyServer); + handler = new NettyHttpClient(); } @Override @@ -27,6 +29,7 @@ public void channelReadComplete(ChannelHandlerContext ctx) { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { try { + //logger.info("channelRead流量接口请求开始,时间为{}", startTime); FullHttpRequest fullRequest = (FullHttpRequest) msg; // String uri = fullRequest.uri(); @@ -35,8 +38,10 @@ public void channelRead(ChannelHandlerContext ctx, Object msg) { // handlerTest(fullRequest, ctx); // } - handler.handle(fullRequest, ctx); - + //handler.handle(fullRequest, ctx); + String host = proxyServer.replaceAll("/", "").split(":")[1]; + int port = Integer.parseInt(proxyServer.replaceAll("/", "").split(":")[2]); + handler.connect(host, port, ctx); } catch(Exception e) { e.printStackTrace(); } finally { diff --git a/02nio/nio02/src/main/java/io/github/kimmking/gateway/inbound/HttpInboundServer.java b/02nio/nio02/src/main/java/io/github/kimmking/gateway/inbound/HttpInboundServer.java index 071fa9bc..d78ca2f2 100644 --- a/02nio/nio02/src/main/java/io/github/kimmking/gateway/inbound/HttpInboundServer.java +++ b/02nio/nio02/src/main/java/io/github/kimmking/gateway/inbound/HttpInboundServer.java @@ -33,10 +33,12 @@ public void run() throws Exception { try { ServerBootstrap b = new ServerBootstrap(); + // windows下SO_BACKLOG默认200,linux和mac默认128 b.option(ChannelOption.SO_BACKLOG, 128) .option(ChannelOption.TCP_NODELAY, true) .option(ChannelOption.SO_KEEPALIVE, true) .option(ChannelOption.SO_REUSEADDR, true) + // 默认32 * 1024最为合适 .option(ChannelOption.SO_RCVBUF, 32 * 1024) .option(ChannelOption.SO_SNDBUF, 32 * 1024) .option(EpollChannelOption.SO_REUSEPORT, true) 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..2893d965 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,55 @@ -//package io.github.kimmking.gateway.outbound; -// -//import io.netty.bootstrap.Bootstrap; -//import io.netty.channel.ChannelFuture; -//import io.netty.channel.ChannelInitializer; -//import io.netty.channel.ChannelOption; -//import io.netty.channel.EventLoopGroup; -//import io.netty.channel.nio.NioEventLoopGroup; -//import io.netty.channel.socket.SocketChannel; -//import io.netty.channel.socket.nio.NioSocketChannel; -//import io.netty.handler.codec.http.HttpRequestEncoder; -//import io.netty.handler.codec.http.HttpResponseDecoder; -// -//public class NettyHttpClient { -// public void connect(String host, int port) throws Exception { -// EventLoopGroup workerGroup = new NioEventLoopGroup(); -// -// try { -// Bootstrap b = new Bootstrap(); -// b.group(workerGroup); -// b.channel(NioSocketChannel.class); -// b.option(ChannelOption.SO_KEEPALIVE, true); -// b.handler(new ChannelInitializer() { -// @Override -// public void initChannel(SocketChannel ch) throws Exception { -// // 客户端接收到的是httpResponse响应,所以要使用HttpResponseDecoder进行解码 -// ch.pipeline().addLast(new HttpResponseDecoder()); -// 客户端发送的是httprequest,所以要使用HttpRequestEncoder进行编码 -// ch.pipeline().addLast(new HttpRequestEncoder()); -// ch.pipeline().addLast(new HttpClientOutboundHandler()); -// } -// }); -// -// // Start the client. -// ChannelFuture f = b.connect(host, port).sync(); -// -// -// f.channel().write(request); -// f.channel().flush(); -// f.channel().closeFuture().sync(); -// } finally { -// workerGroup.shutdownGracefully(); -// } -// -// } -// -// public static void main(String[] args) throws Exception { -// NettyHttpClient client = new NettyHttpClient(); -// client.connect("127.0.0.1", 8844); -// } -//} \ No newline at end of file +package io.github.kimmking.gateway.outbound.netty4; + +import io.netty.bootstrap.Bootstrap; +import io.netty.channel.*; +import io.netty.channel.nio.NioEventLoopGroup; +import io.netty.channel.socket.SocketChannel; +import io.netty.channel.socket.nio.NioSocketChannel; +import io.netty.handler.codec.http.*; + +public class NettyHttpClient { + public void connect(String host, int port, ChannelHandlerContext ctx) throws Exception { + EventLoopGroup workerGroup = new NioEventLoopGroup(); + + try { + Bootstrap b = new Bootstrap(); + b.group(workerGroup); + b.channel(NioSocketChannel.class); + b.option(ChannelOption.SO_KEEPALIVE, true) + .option(ChannelOption.SO_RCVBUF, 32 * 1024); + 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 NettyHttpOutboundHandler(ctx)); + } + }); + + + /*DefaultFullHttpRequest request = new DefaultFullHttpRequest( + HttpVersion.HTTP_1_1, HttpMethod.GET, new URI("/api/hello").toASCIIString()); + // 构建http请求 + request.headers().set(HttpHeaderNames.HOST, host); + request.headers().set(HttpHeaderNames.CONNECTION, + HttpHeaderNames.CONNECTION); + request.headers().set(HttpHeaderNames.CONTENT_LENGTH, + request.content().readableBytes());*/ + // 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", 8088); + } +} 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 deleted file mode 100644 index 6730cd5a..00000000 --- a/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/netty4/NettyHttpClientOutboundHandler.java +++ /dev/null @@ -1,22 +0,0 @@ -package io.github.kimmking.gateway.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/kimmking/gateway/outbound/netty4/NettyHttpOutboundHandler.java b/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/netty4/NettyHttpOutboundHandler.java new file mode 100644 index 00000000..80595074 --- /dev/null +++ b/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/netty4/NettyHttpOutboundHandler.java @@ -0,0 +1,86 @@ +package io.github.kimmking.gateway.outbound.netty4; + +import io.github.kimmking.gateway.util.ByteBufToBytes; +import io.netty.bootstrap.Bootstrap; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +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.*; +import org.apache.http.util.EntityUtils; + +import java.net.URI; + +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 NettyHttpOutboundHandler extends ChannelInboundHandlerAdapter { + private ByteBufToBytes reader; + private ChannelHandlerContext parentCtx; + private int contentLength = 0; + public NettyHttpOutboundHandler(ChannelHandlerContext ctx) { + this.parentCtx = ctx; + } + @Override + public void channelActive(ChannelHandlerContext ctx) + throws Exception { + System.out.println("channelActive"); + /* URI uri = new URI("/api/hello"); + FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri.toASCIIString()); + request.headers().add(HttpHeaderNames.CONNECTION,HttpHeaderValues.KEEP_ALIVE); + request.headers().add(HttpHeaderNames.CONTENT_LENGTH,request.content().readableBytes()); + ctx.writeAndFlush(request);*/ + DefaultFullHttpRequest request = new DefaultFullHttpRequest( + HttpVersion.HTTP_1_1, HttpMethod.GET, new URI("/api/hello").toASCIIString()); + // 构建http请求 + request.headers().set(HttpHeaderNames.HOST, "127.0.0.1"); + request.headers().set(HttpHeaderNames.CONNECTION, + HttpHeaderNames.CONNECTION); + request.headers().set(HttpHeaderNames.CONTENT_LENGTH, + request.content().readableBytes()); + ctx.writeAndFlush(request); + } + + @Override + public void channelRead(ChannelHandlerContext ctx, Object msg) + throws Exception { + System.out.println("channelRead"); + + if (msg instanceof HttpResponse) { + HttpResponse response = (HttpResponse) msg; + System.out.println("CONTENT_TYPE:" + + response.headers().get(HttpHeaderNames.CONTENT_TYPE)); + if (HttpUtil.isContentLengthSet(response)) { + contentLength = (int) HttpUtil.getContentLength(response); + reader = new ByteBufToBytes(contentLength); + } + } + if (msg instanceof HttpContent) { + HttpContent httpContent = (HttpContent) msg; + ByteBuf content = httpContent.content(); + reader.reading(content); + content.release(); + byte[] bytes = reader.readFull(); + System.out.println(new String(bytes)); + if (reader.isEnd()) { + FullHttpResponse response = null; + try { + response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(bytes)); + response.headers().set("Content-Type", "text/plain;charset=UTF-8"); + response.headers().setInt("Content-Length", contentLength); + } catch (Exception e) { + e.printStackTrace(); + response = new DefaultFullHttpResponse(HTTP_1_1, NO_CONTENT); + exceptionCaught(parentCtx, e); + } finally { + parentCtx.write(response); + } + parentCtx.flush(); + ctx.close(); + } + } + } +} \ No newline at end of file diff --git a/02nio/nio02/src/main/java/io/github/kimmking/gateway/util/ByteBufToBytes.java b/02nio/nio02/src/main/java/io/github/kimmking/gateway/util/ByteBufToBytes.java new file mode 100644 index 00000000..7f7ba4b7 --- /dev/null +++ b/02nio/nio02/src/main/java/io/github/kimmking/gateway/util/ByteBufToBytes.java @@ -0,0 +1,37 @@ +package io.github.kimmking.gateway.util; + +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +public class ByteBufToBytes { + private ByteBuf temp; + private boolean end = true; + public ByteBufToBytes(int length) { + temp = Unpooled.buffer(length); + } + public void reading(ByteBuf datas) { + datas.readBytes(temp, datas.readableBytes()); + if (this.temp.writableBytes() != 0) { + end = false; + } else { + end = true; + } + } + public boolean isEnd() { + return end; + } + public byte[] readFull() { + if (end) { + byte[] contentByte = new byte[this.temp.readableBytes()]; + this.temp.readBytes(contentByte); + this.temp.release(); + return contentByte; + } else { + return null; + } + } + public byte[] read(ByteBuf datas) { + byte[] bytes = new byte[datas.readableBytes()]; + datas.readBytes(bytes); + return bytes; + } +} \ No newline at end of file From 2cc8eca2d83d47bb7b3818d9c2c4ed14a197036d Mon Sep 17 00:00:00 2001 From: hiram <1104712460@qq.com> Date: Mon, 2 Nov 2020 11:23:28 +0800 Subject: [PATCH 2/7] =?UTF-8?q?netty=E5=AE=9E=E7=8E=B0http=E5=AE=A2?= =?UTF-8?q?=E6=88=B7=E7=AB=AF=E8=AE=BF=E9=97=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../gateway/NettyServerApplication.java | 13 +- .../gateway/inbound/HttpInboundHandler.java | 10 +- .../outbound/netty4/NettyHttpClient.java | 9 +- .../netty4/NettyHttpOutboundHandler.java | 22 +-- .../httpclient4/HttpOutboundHandler.java | 138 ++++++++++++++++++ .../httpclient4/NamedThreadFactory.java | 32 ++++ .../okhttp/netty4/NettyHttpClient.java | 58 ++++++++ .../netty4/NettyHttpOutboundHandler.java | 88 +++++++++++ .../okhttp/okhttp/OkhttpOutboundHandler.java | 4 + 9 files changed, 349 insertions(+), 25 deletions(-) create mode 100644 02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/okhttp/httpclient4/HttpOutboundHandler.java create mode 100644 02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/okhttp/httpclient4/NamedThreadFactory.java create mode 100644 02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/okhttp/netty4/NettyHttpClient.java create mode 100644 02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/okhttp/netty4/NettyHttpOutboundHandler.java create mode 100644 02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/okhttp/okhttp/OkhttpOutboundHandler.java diff --git a/02nio/nio02/src/main/java/io/github/kimmking/gateway/NettyServerApplication.java b/02nio/nio02/src/main/java/io/github/kimmking/gateway/NettyServerApplication.java index c539b5ec..3c5fec2c 100644 --- a/02nio/nio02/src/main/java/io/github/kimmking/gateway/NettyServerApplication.java +++ b/02nio/nio02/src/main/java/io/github/kimmking/gateway/NettyServerApplication.java @@ -4,17 +4,18 @@ import io.github.kimmking.gateway.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:8088"); + // String proxyServer = System.getProperty("proxyServer","http://www.baidu.com:80"); String proxyPort = System.getProperty("proxyPort","8888"); - - // http://localhost:8888/api/hello ==> gateway API - // http://localhost:8088/api/hello ==> backend service - + + // 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); 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 58a74fa5..db6d8f13 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 @@ -15,12 +15,12 @@ public class HttpInboundHandler extends ChannelInboundHandlerAdapter { private static Logger logger = LoggerFactory.getLogger(HttpInboundHandler.class); private final String proxyServer; private NettyHttpClient handler; - + public HttpInboundHandler(String proxyServer) { this.proxyServer = proxyServer; handler = new NettyHttpClient(); } - + @Override public void channelReadComplete(ChannelHandlerContext ctx) { ctx.flush(); @@ -37,11 +37,9 @@ public void channelRead(ChannelHandlerContext ctx, Object msg) { // if (uri.contains("/test")) { // handlerTest(fullRequest, ctx); // } - + //handler.handle(fullRequest, ctx); - String host = proxyServer.replaceAll("/", "").split(":")[1]; - int port = Integer.parseInt(proxyServer.replaceAll("/", "").split(":")[2]); - handler.connect(host, port, ctx); + handler.connect(proxyServer, ctx); } catch(Exception e) { e.printStackTrace(); } finally { 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 2893d965..eddf90a0 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 @@ -5,10 +5,11 @@ 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.*; +import io.netty.handler.codec.http.HttpRequestEncoder; +import io.netty.handler.codec.http.HttpResponseDecoder; public class NettyHttpClient { - public void connect(String host, int port, ChannelHandlerContext ctx) throws Exception { + public void connect(String proxyServer, ChannelHandlerContext ctx) throws Exception { EventLoopGroup workerGroup = new NioEventLoopGroup(); try { @@ -24,7 +25,7 @@ public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new HttpResponseDecoder()); // 客户端发送的是httprequest,所以要使用HttpRequestEncoder进行编码 ch.pipeline().addLast(new HttpRequestEncoder()); - ch.pipeline().addLast(new NettyHttpOutboundHandler(ctx)); + ch.pipeline().addLast(new NettyHttpOutboundHandler(ctx, proxyServer)); } }); @@ -38,6 +39,8 @@ public void initChannel(SocketChannel ch) throws Exception { request.headers().set(HttpHeaderNames.CONTENT_LENGTH, request.content().readableBytes());*/ // Start the client. + String host = proxyServer.replaceAll("/", "").split(":")[1]; + int port = Integer.parseInt(proxyServer.replaceAll("/", "").split(":")[2]); ChannelFuture f = b.connect(host, port).sync(); /*f.channel().write(request); f.channel().flush();*/ diff --git a/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/netty4/NettyHttpOutboundHandler.java b/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/netty4/NettyHttpOutboundHandler.java index 80595074..46a9254e 100644 --- a/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/netty4/NettyHttpOutboundHandler.java +++ b/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/netty4/NettyHttpOutboundHandler.java @@ -1,15 +1,11 @@ package io.github.kimmking.gateway.outbound.netty4; import io.github.kimmking.gateway.util.ByteBufToBytes; -import io.netty.bootstrap.Bootstrap; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; -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.channel.ChannelHandlerContext; +import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.handler.codec.http.*; -import org.apache.http.util.EntityUtils; import java.net.URI; @@ -21,8 +17,10 @@ public class NettyHttpOutboundHandler extends ChannelInboundHandlerAdapter { private ByteBufToBytes reader; private ChannelHandlerContext parentCtx; private int contentLength = 0; - public NettyHttpOutboundHandler(ChannelHandlerContext ctx) { + private String proxyServer = null; + public NettyHttpOutboundHandler(ChannelHandlerContext ctx, String proxyServer) { this.parentCtx = ctx; + this.proxyServer = proxyServer; } @Override public void channelActive(ChannelHandlerContext ctx) @@ -33,10 +31,14 @@ public void channelActive(ChannelHandlerContext ctx) request.headers().add(HttpHeaderNames.CONNECTION,HttpHeaderValues.KEEP_ALIVE); request.headers().add(HttpHeaderNames.CONTENT_LENGTH,request.content().readableBytes()); ctx.writeAndFlush(request);*/ + String host = proxyServer.replaceAll("/", "").split(":")[1]; DefaultFullHttpRequest request = new DefaultFullHttpRequest( HttpVersion.HTTP_1_1, HttpMethod.GET, new URI("/api/hello").toASCIIString()); - // 构建http请求 - request.headers().set(HttpHeaderNames.HOST, "127.0.0.1"); + /*DefaultFullHttpRequest request = new DefaultFullHttpRequest( + HttpVersion.HTTP_1_1, HttpMethod.GET, new URI("/").toASCIIString());*/ + + // 构建http请求 + request.headers().set(HttpHeaderNames.HOST, host); request.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderNames.CONNECTION); request.headers().set(HttpHeaderNames.CONTENT_LENGTH, @@ -69,7 +71,7 @@ public void channelRead(ChannelHandlerContext ctx, Object msg) FullHttpResponse response = null; try { response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(bytes)); - response.headers().set("Content-Type", "text/plain;charset=UTF-8"); + response.headers().set("Content-Type", "text/html;charset=UTF-8"); response.headers().setInt("Content-Length", contentLength); } catch (Exception e) { e.printStackTrace(); diff --git a/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/okhttp/httpclient4/HttpOutboundHandler.java b/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/okhttp/httpclient4/HttpOutboundHandler.java new file mode 100644 index 00000000..29af3c3e --- /dev/null +++ b/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/okhttp/httpclient4/HttpOutboundHandler.java @@ -0,0 +1,138 @@ +package io.github.kimmking.gateway.outbound.okhttp.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())); + +// for (Header e : endpointResponse.getAllHeaders()) { +// //response.headers().set(e.getName(),e.getValue()); +// System.out.println(e.getName() + " => " + e.getValue()); +// } + + } catch (Exception e) { + e.printStackTrace(); + response = new DefaultFullHttpResponse(HTTP_1_1, NO_CONTENT); + exceptionCaught(ctx, e); + } finally { + if (fullRequest != null) { + if (!HttpUtil.isKeepAlive(fullRequest)) { + ctx.write(response).addListener(ChannelFutureListener.CLOSE); + } else { + //response.headers().set(CONNECTION, KEEP_ALIVE); + ctx.write(response); + } + } + ctx.flush(); + //ctx.close(); + } + + } + + public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { + cause.printStackTrace(); + ctx.close(); + } + + +} diff --git a/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/okhttp/httpclient4/NamedThreadFactory.java b/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/okhttp/httpclient4/NamedThreadFactory.java new file mode 100644 index 00000000..3f73387f --- /dev/null +++ b/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/okhttp/httpclient4/NamedThreadFactory.java @@ -0,0 +1,32 @@ +package io.github.kimmking.gateway.outbound.okhttp.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/kimmking/gateway/outbound/okhttp/netty4/NettyHttpClient.java b/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/okhttp/netty4/NettyHttpClient.java new file mode 100644 index 00000000..8d244ade --- /dev/null +++ b/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/okhttp/netty4/NettyHttpClient.java @@ -0,0 +1,58 @@ +package io.github.kimmking.gateway.outbound.okhttp.netty4; + +import io.netty.bootstrap.Bootstrap; +import io.netty.channel.*; +import io.netty.channel.nio.NioEventLoopGroup; +import io.netty.channel.socket.SocketChannel; +import io.netty.channel.socket.nio.NioSocketChannel; +import io.netty.handler.codec.http.HttpRequestEncoder; +import io.netty.handler.codec.http.HttpResponseDecoder; + +public class NettyHttpClient { + public void connect(String proxyServer, ChannelHandlerContext ctx) throws Exception { + EventLoopGroup workerGroup = new NioEventLoopGroup(); + + try { + Bootstrap b = new Bootstrap(); + b.group(workerGroup); + b.channel(NioSocketChannel.class); + b.option(ChannelOption.SO_KEEPALIVE, true) + .option(ChannelOption.SO_RCVBUF, 32 * 1024); + 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 NettyHttpOutboundHandler(ctx, proxyServer)); + } + }); + + + /*DefaultFullHttpRequest request = new DefaultFullHttpRequest( + HttpVersion.HTTP_1_1, HttpMethod.GET, new URI("/api/hello").toASCIIString()); + // 构建http请求 + request.headers().set(HttpHeaderNames.HOST, host); + request.headers().set(HttpHeaderNames.CONNECTION, + HttpHeaderNames.CONNECTION); + request.headers().set(HttpHeaderNames.CONTENT_LENGTH, + request.content().readableBytes());*/ + // Start the client. + String host = proxyServer.replaceAll("/", "").split(":")[1]; + int port = Integer.parseInt(proxyServer.replaceAll("/", "").split(":")[2]); + 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", 8088); + } +} diff --git a/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/okhttp/netty4/NettyHttpOutboundHandler.java b/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/okhttp/netty4/NettyHttpOutboundHandler.java new file mode 100644 index 00000000..7c8df8d1 --- /dev/null +++ b/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/okhttp/netty4/NettyHttpOutboundHandler.java @@ -0,0 +1,88 @@ +package io.github.kimmking.gateway.outbound.okhttp.netty4; + +import io.github.kimmking.gateway.util.ByteBufToBytes; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelInboundHandlerAdapter; +import io.netty.handler.codec.http.*; + +import java.net.URI; + +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 NettyHttpOutboundHandler extends ChannelInboundHandlerAdapter { + private ByteBufToBytes reader; + private ChannelHandlerContext parentCtx; + private int contentLength = 0; + private String proxyServer = null; + public NettyHttpOutboundHandler(ChannelHandlerContext ctx, String proxyServer) { + this.parentCtx = ctx; + this.proxyServer = proxyServer; + } + @Override + public void channelActive(ChannelHandlerContext ctx) + throws Exception { + System.out.println("channelActive"); + /* URI uri = new URI("/api/hello"); + FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri.toASCIIString()); + request.headers().add(HttpHeaderNames.CONNECTION,HttpHeaderValues.KEEP_ALIVE); + request.headers().add(HttpHeaderNames.CONTENT_LENGTH,request.content().readableBytes()); + ctx.writeAndFlush(request);*/ + String host = proxyServer.replaceAll("/", "").split(":")[1]; + DefaultFullHttpRequest request = new DefaultFullHttpRequest( + HttpVersion.HTTP_1_1, HttpMethod.GET, new URI("/api/hello").toASCIIString()); + /*DefaultFullHttpRequest request = new DefaultFullHttpRequest( + HttpVersion.HTTP_1_1, HttpMethod.GET, new URI("/").toASCIIString());*/ + + // 构建http请求 + request.headers().set(HttpHeaderNames.HOST, host); + request.headers().set(HttpHeaderNames.CONNECTION, + HttpHeaderNames.CONNECTION); + request.headers().set(HttpHeaderNames.CONTENT_LENGTH, + request.content().readableBytes()); + ctx.writeAndFlush(request); + } + + @Override + public void channelRead(ChannelHandlerContext ctx, Object msg) + throws Exception { + System.out.println("channelRead"); + + if (msg instanceof HttpResponse) { + HttpResponse response = (HttpResponse) msg; + System.out.println("CONTENT_TYPE:" + + response.headers().get(HttpHeaderNames.CONTENT_TYPE)); + if (HttpUtil.isContentLengthSet(response)) { + contentLength = (int) HttpUtil.getContentLength(response); + reader = new ByteBufToBytes(contentLength); + } + } + if (msg instanceof HttpContent) { + HttpContent httpContent = (HttpContent) msg; + ByteBuf content = httpContent.content(); + reader.reading(content); + content.release(); + byte[] bytes = reader.readFull(); + System.out.println(new String(bytes)); + if (reader.isEnd()) { + FullHttpResponse response = null; + try { + response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(bytes)); + response.headers().set("Content-Type", "text/html;charset=UTF-8"); + response.headers().setInt("Content-Length", contentLength); + } catch (Exception e) { + e.printStackTrace(); + response = new DefaultFullHttpResponse(HTTP_1_1, NO_CONTENT); + exceptionCaught(parentCtx, e); + } finally { + parentCtx.write(response); + } + parentCtx.flush(); + ctx.close(); + } + } + } +} \ No newline at end of file diff --git a/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/okhttp/okhttp/OkhttpOutboundHandler.java b/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/okhttp/okhttp/OkhttpOutboundHandler.java new file mode 100644 index 00000000..b813b037 --- /dev/null +++ b/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/okhttp/okhttp/OkhttpOutboundHandler.java @@ -0,0 +1,4 @@ +package io.github.kimmking.gateway.outbound.okhttp.okhttp; + +public class OkhttpOutboundHandler { +} From 6c1d0859c120fc2704dce8ca9b40d73fd5c9d5dd Mon Sep 17 00:00:00 2001 From: hiram <1104712460@qq.com> Date: Mon, 2 Nov 2020 12:07:23 +0800 Subject: [PATCH 3/7] =?UTF-8?q?netty=E5=AE=9E=E7=8E=B0http=E5=AE=A2?= =?UTF-8?q?=E6=88=B7=E7=AB=AF=E8=AE=BF=E9=97=AE=E4=BF=AE=E6=94=B9=E9=83=A8?= =?UTF-8?q?=E5=88=86=E9=80=BB=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../gateway/inbound/HttpInboundHandler.java | 13 +- .../outbound/netty4/NettyHttpClient.java | 18 ++- .../netty4/NettyHttpOutboundHandler.java | 24 +-- .../httpclient4/HttpOutboundHandler.java | 138 ------------------ .../httpclient4/NamedThreadFactory.java | 32 ---- .../okhttp/netty4/NettyHttpClient.java | 58 -------- .../netty4/NettyHttpOutboundHandler.java | 88 ----------- .../okhttp/okhttp/OkhttpOutboundHandler.java | 4 - 8 files changed, 35 insertions(+), 340 deletions(-) delete mode 100644 02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/okhttp/httpclient4/HttpOutboundHandler.java delete mode 100644 02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/okhttp/httpclient4/NamedThreadFactory.java delete mode 100644 02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/okhttp/netty4/NettyHttpClient.java delete mode 100644 02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/okhttp/netty4/NettyHttpOutboundHandler.java delete mode 100644 02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/okhttp/okhttp/OkhttpOutboundHandler.java 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 db6d8f13..fd004b4f 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,11 +1,13 @@ package io.github.kimmking.gateway.inbound; +import io.github.kimmking.gateway.filter.HttpMethodRequestFilter; import io.github.kimmking.gateway.outbound.httpclient4.HttpOutboundHandler; import io.github.kimmking.gateway.outbound.netty4.NettyHttpClient; import io.github.kimmking.gateway.outbound.netty4.NettyHttpOutboundHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.handler.codec.http.FullHttpRequest; +import io.netty.handler.codec.http.HttpHeaderNames; import io.netty.util.ReferenceCountUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -18,7 +20,7 @@ public class HttpInboundHandler extends ChannelInboundHandlerAdapter { public HttpInboundHandler(String proxyServer) { this.proxyServer = proxyServer; - handler = new NettyHttpClient(); + handler = new NettyHttpClient(proxyServer); } @Override @@ -32,14 +34,17 @@ public void channelRead(ChannelHandlerContext ctx, Object msg) { //logger.info("channelRead流量接口请求开始,时间为{}", startTime); FullHttpRequest fullRequest = (FullHttpRequest) msg; -// String uri = fullRequest.uri(); -// //logger.info("接收到的请求url为{}", uri); + String uri = fullRequest.uri(); + fullRequest.headers().get(HttpHeaderNames.CONTENT_TYPE); + //System.out.println("接收到的请求url为" + uri); // if (uri.contains("/test")) { // handlerTest(fullRequest, ctx); // } //handler.handle(fullRequest, ctx); - handler.connect(proxyServer, ctx); + HttpMethodRequestFilter myFirstHttpRequestFilter = new HttpMethodRequestFilter(); + myFirstHttpRequestFilter.filter(fullRequest, ctx); + handler.connect(fullRequest, ctx); } catch(Exception e) { e.printStackTrace(); } finally { 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 eddf90a0..e58c3daf 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 @@ -5,11 +5,19 @@ import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; +import io.netty.handler.codec.http.FullHttpRequest; +import io.netty.handler.codec.http.HttpHeaderNames; import io.netty.handler.codec.http.HttpRequestEncoder; import io.netty.handler.codec.http.HttpResponseDecoder; public class NettyHttpClient { - public void connect(String proxyServer, ChannelHandlerContext ctx) throws Exception { + private String backendUrl; + + public NettyHttpClient(String backendUrl) { + this.backendUrl = backendUrl; + } + + public void connect(FullHttpRequest fullHttpRequest, ChannelHandlerContext ctx) throws Exception { EventLoopGroup workerGroup = new NioEventLoopGroup(); try { @@ -25,7 +33,7 @@ public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new HttpResponseDecoder()); // 客户端发送的是httprequest,所以要使用HttpRequestEncoder进行编码 ch.pipeline().addLast(new HttpRequestEncoder()); - ch.pipeline().addLast(new NettyHttpOutboundHandler(ctx, proxyServer)); + ch.pipeline().addLast(new NettyHttpOutboundHandler(ctx, fullHttpRequest, backendUrl)); } }); @@ -39,8 +47,8 @@ public void initChannel(SocketChannel ch) throws Exception { request.headers().set(HttpHeaderNames.CONTENT_LENGTH, request.content().readableBytes());*/ // Start the client. - String host = proxyServer.replaceAll("/", "").split(":")[1]; - int port = Integer.parseInt(proxyServer.replaceAll("/", "").split(":")[2]); + String host = backendUrl.replaceAll("/", "").split(":")[1]; + int port = Integer.parseInt(backendUrl.replaceAll("/", "").split(":")[2]); ChannelFuture f = b.connect(host, port).sync(); /*f.channel().write(request); f.channel().flush();*/ @@ -52,7 +60,7 @@ public void initChannel(SocketChannel ch) throws Exception { } public static void main(String[] args) throws Exception { - NettyHttpClient client = new NettyHttpClient(); + // NettyHttpClient client = new NettyHttpClient(); //client.connect("127.0.0.1", 8088); } } diff --git a/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/netty4/NettyHttpOutboundHandler.java b/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/netty4/NettyHttpOutboundHandler.java index 46a9254e..dd411d67 100644 --- a/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/netty4/NettyHttpOutboundHandler.java +++ b/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/netty4/NettyHttpOutboundHandler.java @@ -17,23 +17,25 @@ public class NettyHttpOutboundHandler extends ChannelInboundHandlerAdapter { private ByteBufToBytes reader; private ChannelHandlerContext parentCtx; private int contentLength = 0; - private String proxyServer = null; - public NettyHttpOutboundHandler(ChannelHandlerContext ctx, String proxyServer) { + private FullHttpRequest fullHttpRequest = null; + private String backendUrl; + public NettyHttpOutboundHandler(ChannelHandlerContext ctx, FullHttpRequest fullHttpRequest, String backendUrl) { this.parentCtx = ctx; - this.proxyServer = proxyServer; + this.fullHttpRequest = fullHttpRequest; + this.backendUrl = backendUrl; } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { - System.out.println("channelActive"); + //System.out.println("channelActive"); /* URI uri = new URI("/api/hello"); FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri.toASCIIString()); request.headers().add(HttpHeaderNames.CONNECTION,HttpHeaderValues.KEEP_ALIVE); request.headers().add(HttpHeaderNames.CONTENT_LENGTH,request.content().readableBytes()); ctx.writeAndFlush(request);*/ - String host = proxyServer.replaceAll("/", "").split(":")[1]; - DefaultFullHttpRequest request = new DefaultFullHttpRequest( - HttpVersion.HTTP_1_1, HttpMethod.GET, new URI("/api/hello").toASCIIString()); + String host = backendUrl.replaceAll("/", "").split(":")[1]; + DefaultFullHttpRequest request = new DefaultFullHttpRequest( + HttpVersion.HTTP_1_1, fullHttpRequest.method(), fullHttpRequest.uri()); /*DefaultFullHttpRequest request = new DefaultFullHttpRequest( HttpVersion.HTTP_1_1, HttpMethod.GET, new URI("/").toASCIIString());*/ @@ -49,12 +51,12 @@ public void channelActive(ChannelHandlerContext ctx) @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { - System.out.println("channelRead"); + //System.out.println("channelRead"); if (msg instanceof HttpResponse) { HttpResponse response = (HttpResponse) msg; - System.out.println("CONTENT_TYPE:" - + response.headers().get(HttpHeaderNames.CONTENT_TYPE)); + /*System.out.println("CONTENT_TYPE:" + + response.headers().get(HttpHeaderNames.CONTENT_TYPE));*/ if (HttpUtil.isContentLengthSet(response)) { contentLength = (int) HttpUtil.getContentLength(response); reader = new ByteBufToBytes(contentLength); @@ -66,7 +68,7 @@ public void channelRead(ChannelHandlerContext ctx, Object msg) reader.reading(content); content.release(); byte[] bytes = reader.readFull(); - System.out.println(new String(bytes)); + //System.out.println(new String(bytes)); if (reader.isEnd()) { FullHttpResponse response = null; try { diff --git a/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/okhttp/httpclient4/HttpOutboundHandler.java b/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/okhttp/httpclient4/HttpOutboundHandler.java deleted file mode 100644 index 29af3c3e..00000000 --- a/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/okhttp/httpclient4/HttpOutboundHandler.java +++ /dev/null @@ -1,138 +0,0 @@ -package io.github.kimmking.gateway.outbound.okhttp.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())); - -// for (Header e : endpointResponse.getAllHeaders()) { -// //response.headers().set(e.getName(),e.getValue()); -// System.out.println(e.getName() + " => " + e.getValue()); -// } - - } catch (Exception e) { - e.printStackTrace(); - response = new DefaultFullHttpResponse(HTTP_1_1, NO_CONTENT); - exceptionCaught(ctx, e); - } finally { - if (fullRequest != null) { - if (!HttpUtil.isKeepAlive(fullRequest)) { - ctx.write(response).addListener(ChannelFutureListener.CLOSE); - } else { - //response.headers().set(CONNECTION, KEEP_ALIVE); - ctx.write(response); - } - } - ctx.flush(); - //ctx.close(); - } - - } - - public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { - cause.printStackTrace(); - ctx.close(); - } - - -} diff --git a/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/okhttp/httpclient4/NamedThreadFactory.java b/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/okhttp/httpclient4/NamedThreadFactory.java deleted file mode 100644 index 3f73387f..00000000 --- a/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/okhttp/httpclient4/NamedThreadFactory.java +++ /dev/null @@ -1,32 +0,0 @@ -package io.github.kimmking.gateway.outbound.okhttp.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/kimmking/gateway/outbound/okhttp/netty4/NettyHttpClient.java b/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/okhttp/netty4/NettyHttpClient.java deleted file mode 100644 index 8d244ade..00000000 --- a/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/okhttp/netty4/NettyHttpClient.java +++ /dev/null @@ -1,58 +0,0 @@ -package io.github.kimmking.gateway.outbound.okhttp.netty4; - -import io.netty.bootstrap.Bootstrap; -import io.netty.channel.*; -import io.netty.channel.nio.NioEventLoopGroup; -import io.netty.channel.socket.SocketChannel; -import io.netty.channel.socket.nio.NioSocketChannel; -import io.netty.handler.codec.http.HttpRequestEncoder; -import io.netty.handler.codec.http.HttpResponseDecoder; - -public class NettyHttpClient { - public void connect(String proxyServer, ChannelHandlerContext ctx) throws Exception { - EventLoopGroup workerGroup = new NioEventLoopGroup(); - - try { - Bootstrap b = new Bootstrap(); - b.group(workerGroup); - b.channel(NioSocketChannel.class); - b.option(ChannelOption.SO_KEEPALIVE, true) - .option(ChannelOption.SO_RCVBUF, 32 * 1024); - 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 NettyHttpOutboundHandler(ctx, proxyServer)); - } - }); - - - /*DefaultFullHttpRequest request = new DefaultFullHttpRequest( - HttpVersion.HTTP_1_1, HttpMethod.GET, new URI("/api/hello").toASCIIString()); - // 构建http请求 - request.headers().set(HttpHeaderNames.HOST, host); - request.headers().set(HttpHeaderNames.CONNECTION, - HttpHeaderNames.CONNECTION); - request.headers().set(HttpHeaderNames.CONTENT_LENGTH, - request.content().readableBytes());*/ - // Start the client. - String host = proxyServer.replaceAll("/", "").split(":")[1]; - int port = Integer.parseInt(proxyServer.replaceAll("/", "").split(":")[2]); - 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", 8088); - } -} diff --git a/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/okhttp/netty4/NettyHttpOutboundHandler.java b/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/okhttp/netty4/NettyHttpOutboundHandler.java deleted file mode 100644 index 7c8df8d1..00000000 --- a/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/okhttp/netty4/NettyHttpOutboundHandler.java +++ /dev/null @@ -1,88 +0,0 @@ -package io.github.kimmking.gateway.outbound.okhttp.netty4; - -import io.github.kimmking.gateway.util.ByteBufToBytes; -import io.netty.buffer.ByteBuf; -import io.netty.buffer.Unpooled; -import io.netty.channel.ChannelHandlerContext; -import io.netty.channel.ChannelInboundHandlerAdapter; -import io.netty.handler.codec.http.*; - -import java.net.URI; - -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 NettyHttpOutboundHandler extends ChannelInboundHandlerAdapter { - private ByteBufToBytes reader; - private ChannelHandlerContext parentCtx; - private int contentLength = 0; - private String proxyServer = null; - public NettyHttpOutboundHandler(ChannelHandlerContext ctx, String proxyServer) { - this.parentCtx = ctx; - this.proxyServer = proxyServer; - } - @Override - public void channelActive(ChannelHandlerContext ctx) - throws Exception { - System.out.println("channelActive"); - /* URI uri = new URI("/api/hello"); - FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri.toASCIIString()); - request.headers().add(HttpHeaderNames.CONNECTION,HttpHeaderValues.KEEP_ALIVE); - request.headers().add(HttpHeaderNames.CONTENT_LENGTH,request.content().readableBytes()); - ctx.writeAndFlush(request);*/ - String host = proxyServer.replaceAll("/", "").split(":")[1]; - DefaultFullHttpRequest request = new DefaultFullHttpRequest( - HttpVersion.HTTP_1_1, HttpMethod.GET, new URI("/api/hello").toASCIIString()); - /*DefaultFullHttpRequest request = new DefaultFullHttpRequest( - HttpVersion.HTTP_1_1, HttpMethod.GET, new URI("/").toASCIIString());*/ - - // 构建http请求 - request.headers().set(HttpHeaderNames.HOST, host); - request.headers().set(HttpHeaderNames.CONNECTION, - HttpHeaderNames.CONNECTION); - request.headers().set(HttpHeaderNames.CONTENT_LENGTH, - request.content().readableBytes()); - ctx.writeAndFlush(request); - } - - @Override - public void channelRead(ChannelHandlerContext ctx, Object msg) - throws Exception { - System.out.println("channelRead"); - - if (msg instanceof HttpResponse) { - HttpResponse response = (HttpResponse) msg; - System.out.println("CONTENT_TYPE:" - + response.headers().get(HttpHeaderNames.CONTENT_TYPE)); - if (HttpUtil.isContentLengthSet(response)) { - contentLength = (int) HttpUtil.getContentLength(response); - reader = new ByteBufToBytes(contentLength); - } - } - if (msg instanceof HttpContent) { - HttpContent httpContent = (HttpContent) msg; - ByteBuf content = httpContent.content(); - reader.reading(content); - content.release(); - byte[] bytes = reader.readFull(); - System.out.println(new String(bytes)); - if (reader.isEnd()) { - FullHttpResponse response = null; - try { - response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(bytes)); - response.headers().set("Content-Type", "text/html;charset=UTF-8"); - response.headers().setInt("Content-Length", contentLength); - } catch (Exception e) { - e.printStackTrace(); - response = new DefaultFullHttpResponse(HTTP_1_1, NO_CONTENT); - exceptionCaught(parentCtx, e); - } finally { - parentCtx.write(response); - } - parentCtx.flush(); - ctx.close(); - } - } - } -} \ No newline at end of file diff --git a/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/okhttp/okhttp/OkhttpOutboundHandler.java b/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/okhttp/okhttp/OkhttpOutboundHandler.java deleted file mode 100644 index b813b037..00000000 --- a/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/okhttp/okhttp/OkhttpOutboundHandler.java +++ /dev/null @@ -1,4 +0,0 @@ -package io.github.kimmking.gateway.outbound.okhttp.okhttp; - -public class OkhttpOutboundHandler { -} From 33f94b355860dc7fa807f5e77903a74792af66fe Mon Sep 17 00:00:00 2001 From: hiram <1104712460@qq.com> Date: Mon, 2 Nov 2020 13:31:24 +0800 Subject: [PATCH 4/7] =?UTF-8?q?=E6=B7=BB=E5=8A=A0filter?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../gateway/NettyServerApplication.java | 4 +- .../filter/HttpMethodRequestFilter.java | 43 +++++++++++++++++++ .../gateway/filter/UriHttpRequestFilter.java | 23 ++++++++++ .../gateway/inbound/HttpInboundHandler.java | 7 ++- .../outbound/netty4/NettyHttpClient.java | 3 +- 5 files changed, 75 insertions(+), 5 deletions(-) create mode 100644 02nio/nio02/src/main/java/io/github/kimmking/gateway/filter/HttpMethodRequestFilter.java create mode 100644 02nio/nio02/src/main/java/io/github/kimmking/gateway/filter/UriHttpRequestFilter.java diff --git a/02nio/nio02/src/main/java/io/github/kimmking/gateway/NettyServerApplication.java b/02nio/nio02/src/main/java/io/github/kimmking/gateway/NettyServerApplication.java index 3c5fec2c..aca1db72 100644 --- a/02nio/nio02/src/main/java/io/github/kimmking/gateway/NettyServerApplication.java +++ b/02nio/nio02/src/main/java/io/github/kimmking/gateway/NettyServerApplication.java @@ -10,7 +10,7 @@ public class NettyServerApplication { public static void main(String[] args) { String proxyServer = System.getProperty("proxyServer","http://localhost:8088"); - // String proxyServer = System.getProperty("proxyServer","http://www.baidu.com:80"); + //String proxyServer = System.getProperty("proxyServer","http://www.baidu.com"); String proxyPort = System.getProperty("proxyPort","8888"); // http://localhost:8888/api/hello ==> gateway API @@ -19,7 +19,7 @@ public static void main(String[] args) { 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); + System.out.println(GATEWAY_NAME + " " + GATEWAY_VERSION +" started at http://localhost:" + port + "/api/hello for server:" + proxyServer + "/api/hello"); try { server.run(); } catch (Exception ex){ diff --git a/02nio/nio02/src/main/java/io/github/kimmking/gateway/filter/HttpMethodRequestFilter.java b/02nio/nio02/src/main/java/io/github/kimmking/gateway/filter/HttpMethodRequestFilter.java new file mode 100644 index 00000000..c9d025c1 --- /dev/null +++ b/02nio/nio02/src/main/java/io/github/kimmking/gateway/filter/HttpMethodRequestFilter.java @@ -0,0 +1,43 @@ +package io.github.kimmking.gateway.filter; + +import io.netty.buffer.Unpooled; +import io.netty.channel.ChannelFutureListener; +import io.netty.channel.ChannelHandlerContext; +import io.netty.handler.codec.http.*; + +import java.io.UnsupportedEncodingException; + +import static io.netty.handler.codec.http.HttpResponseStatus.*; +import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1; + + +/** + * 过滤http请求,如果是Post就返回错误信息,get请求就通过 + */ +public class HttpMethodRequestFilter implements HttpRequestFilter { + + @Override + public void filter(final FullHttpRequest fullRequest, final ChannelHandlerContext ctx) { + HttpMethod method = fullRequest.method(); + if (method.equals(HttpMethod.POST)) { + FullHttpResponse response = null; + try { + response = new DefaultFullHttpResponse(HTTP_1_1, METHOD_NOT_ALLOWED); + } catch (Exception e) { + e.printStackTrace(); + 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); + } + } + ctx.flush(); + ctx.close(); + } + } + } +} diff --git a/02nio/nio02/src/main/java/io/github/kimmking/gateway/filter/UriHttpRequestFilter.java b/02nio/nio02/src/main/java/io/github/kimmking/gateway/filter/UriHttpRequestFilter.java new file mode 100644 index 00000000..eb0efe42 --- /dev/null +++ b/02nio/nio02/src/main/java/io/github/kimmking/gateway/filter/UriHttpRequestFilter.java @@ -0,0 +1,23 @@ +package io.github.kimmking.gateway.filter; + +import io.netty.channel.ChannelHandlerContext; +import io.netty.handler.codec.http.DefaultFullHttpResponse; +import io.netty.handler.codec.http.FullHttpRequest; + +import static io.netty.handler.codec.http.HttpResponseStatus.NOT_FOUND; +import static io.netty.handler.codec.http.HttpResponseStatus.NO_CONTENT; +import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1; + +public class UriHttpRequestFilter implements HttpRequestFilter{ + @Override + public void filter(final FullHttpRequest fullRequest, ChannelHandlerContext ctx) { + String uri = fullRequest.uri(); + System.out.println("uri: " + uri); + if (!uri.contains("api/hello")) { + DefaultFullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND); + ctx.write(response); + ctx.flush(); + ctx.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 fd004b4f..f43423a5 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,7 @@ package io.github.kimmking.gateway.inbound; import io.github.kimmking.gateway.filter.HttpMethodRequestFilter; +import io.github.kimmking.gateway.filter.UriHttpRequestFilter; import io.github.kimmking.gateway.outbound.httpclient4.HttpOutboundHandler; import io.github.kimmking.gateway.outbound.netty4.NettyHttpClient; import io.github.kimmking.gateway.outbound.netty4.NettyHttpOutboundHandler; @@ -42,8 +43,10 @@ public void channelRead(ChannelHandlerContext ctx, Object msg) { // } //handler.handle(fullRequest, ctx); - HttpMethodRequestFilter myFirstHttpRequestFilter = new HttpMethodRequestFilter(); - myFirstHttpRequestFilter.filter(fullRequest, ctx); + HttpMethodRequestFilter methodHttpRequestFilter = new HttpMethodRequestFilter(); + methodHttpRequestFilter.filter(fullRequest, ctx); + // UriHttpRequestFilter uriHttpRequestFilter = new UriHttpRequestFilter(); + // uriHttpRequestFilter.filter(fullRequest, ctx); handler.connect(fullRequest, ctx); } 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 e58c3daf..a654fdbf 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 @@ -48,7 +48,8 @@ public void initChannel(SocketChannel ch) throws Exception { request.content().readableBytes());*/ // Start the client. String host = backendUrl.replaceAll("/", "").split(":")[1]; - int port = Integer.parseInt(backendUrl.replaceAll("/", "").split(":")[2]); + String[] split = backendUrl.replaceAll("/", "").split(":"); + int port = split.length < 3 ? 80 : Integer.parseInt(split[2]); ChannelFuture f = b.connect(host, port).sync(); /*f.channel().write(request); f.channel().flush();*/ From c4a39a319be06ff2c8837132154b9ce6eb1569eb Mon Sep 17 00:00:00 2001 From: hiram <1104712460@qq.com> Date: Mon, 2 Nov 2020 15:35:10 +0800 Subject: [PATCH 5/7] =?UTF-8?q?=E6=B7=BB=E5=8A=A0Router?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../gateway/NettyServerApplication.java | 14 ++++++--- .../gateway/inbound/HttpInboundHandler.java | 15 ++++----- .../inbound/HttpInboundInitializer.java | 10 +++--- .../gateway/inbound/HttpInboundServer.java | 10 +++--- .../outbound/netty4/NettyHttpClient.java | 30 +++++++++--------- .../netty4/NettyHttpOutboundHandler.java | 3 +- .../router/MyFirstHttpEndpointRouter.java | 31 +++++++++++++++++++ 7 files changed, 78 insertions(+), 35 deletions(-) create mode 100644 02nio/nio02/src/main/java/io/github/kimmking/gateway/router/MyFirstHttpEndpointRouter.java diff --git a/02nio/nio02/src/main/java/io/github/kimmking/gateway/NettyServerApplication.java b/02nio/nio02/src/main/java/io/github/kimmking/gateway/NettyServerApplication.java index aca1db72..af184852 100644 --- a/02nio/nio02/src/main/java/io/github/kimmking/gateway/NettyServerApplication.java +++ b/02nio/nio02/src/main/java/io/github/kimmking/gateway/NettyServerApplication.java @@ -3,14 +3,20 @@ import io.github.kimmking.gateway.inbound.HttpInboundServer; +import java.util.ArrayList; +import java.util.List; + 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:8088"); - //String proxyServer = System.getProperty("proxyServer","http://www.baidu.com"); + String proxyServer1 = System.getProperty("proxyServer","http://localhost:8088/api/hello"); + String proxyServer2 = System.getProperty("proxyServer","http://www.baidu.com"); + ArrayList proxyServerList = new ArrayList<>(); + proxyServerList.add(proxyServer1); + proxyServerList.add(proxyServer2); String proxyPort = System.getProperty("proxyPort","8888"); // http://localhost:8888/api/hello ==> gateway API @@ -18,8 +24,8 @@ public static void main(String[] args) { 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 + "/api/hello for server:" + proxyServer + "/api/hello"); + HttpInboundServer server = new HttpInboundServer(port, proxyServerList); + System.out.println(GATEWAY_NAME + " " + GATEWAY_VERSION +" started at http://localhost:" + port + "/api/hello for server:http://localhost:8088/api/hello or http://www.baidu.com"); try { server.run(); } catch (Exception ex){ 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 f43423a5..df0f5652 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 @@ -5,23 +5,25 @@ import io.github.kimmking.gateway.outbound.httpclient4.HttpOutboundHandler; import io.github.kimmking.gateway.outbound.netty4.NettyHttpClient; import io.github.kimmking.gateway.outbound.netty4.NettyHttpOutboundHandler; +import io.github.kimmking.gateway.util.ByteBufToBytes; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; -import io.netty.handler.codec.http.FullHttpRequest; -import io.netty.handler.codec.http.HttpHeaderNames; +import io.netty.handler.codec.http.*; import io.netty.util.ReferenceCountUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.List; + public class HttpInboundHandler extends ChannelInboundHandlerAdapter { private static Logger logger = LoggerFactory.getLogger(HttpInboundHandler.class); - private final String proxyServer; + private final List proxyServerList; private NettyHttpClient handler; - public HttpInboundHandler(String proxyServer) { - this.proxyServer = proxyServer; - handler = new NettyHttpClient(proxyServer); + public HttpInboundHandler(List proxyServerList) { + this.proxyServerList = proxyServerList; + handler = new NettyHttpClient(proxyServerList); } @Override @@ -32,7 +34,6 @@ public void channelReadComplete(ChannelHandlerContext ctx) { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { try { - //logger.info("channelRead流量接口请求开始,时间为{}", startTime); FullHttpRequest fullRequest = (FullHttpRequest) msg; String uri = fullRequest.uri(); diff --git a/02nio/nio02/src/main/java/io/github/kimmking/gateway/inbound/HttpInboundInitializer.java b/02nio/nio02/src/main/java/io/github/kimmking/gateway/inbound/HttpInboundInitializer.java index d902b4c8..dd2d47d8 100644 --- a/02nio/nio02/src/main/java/io/github/kimmking/gateway/inbound/HttpInboundInitializer.java +++ b/02nio/nio02/src/main/java/io/github/kimmking/gateway/inbound/HttpInboundInitializer.java @@ -6,12 +6,14 @@ import io.netty.handler.codec.http.HttpObjectAggregator; import io.netty.handler.codec.http.HttpServerCodec; +import java.util.List; + public class HttpInboundInitializer extends ChannelInitializer { - private String proxyServer; + private List proxyServerList; - public HttpInboundInitializer(String proxyServer) { - this.proxyServer = proxyServer; + public HttpInboundInitializer(List proxyServerList) { + this.proxyServerList = proxyServerList; } @Override @@ -23,6 +25,6 @@ public void initChannel(SocketChannel ch) { p.addLast(new HttpServerCodec()); //p.addLast(new HttpServerExpectContinueHandler()); p.addLast(new HttpObjectAggregator(1024 * 1024)); - p.addLast(new HttpInboundHandler(this.proxyServer)); + p.addLast(new HttpInboundHandler(this.proxyServerList)); } } diff --git a/02nio/nio02/src/main/java/io/github/kimmking/gateway/inbound/HttpInboundServer.java b/02nio/nio02/src/main/java/io/github/kimmking/gateway/inbound/HttpInboundServer.java index d78ca2f2..361568d0 100644 --- a/02nio/nio02/src/main/java/io/github/kimmking/gateway/inbound/HttpInboundServer.java +++ b/02nio/nio02/src/main/java/io/github/kimmking/gateway/inbound/HttpInboundServer.java @@ -13,17 +13,19 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.List; + public class HttpInboundServer { private static Logger logger = LoggerFactory.getLogger(HttpInboundServer.class); private int port; - private String proxyServer; + private List proxyServerList; - public HttpInboundServer(int port, String proxyServer) { + public HttpInboundServer(int port, List proxyServerList) { this.port=port; - this.proxyServer = proxyServer; + this.proxyServerList = proxyServerList; } public void run() throws Exception { @@ -46,7 +48,7 @@ public void run() throws Exception { .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) - .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new HttpInboundInitializer(this.proxyServer)); + .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new HttpInboundInitializer(this.proxyServerList)); Channel ch = b.bind(port).sync().channel(); logger.info("开启netty http服务器,监听地址和端口为 http://127.0.0.1:" + port + '/'); 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 a654fdbf..55a224ca 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,23 +1,28 @@ package io.github.kimmking.gateway.outbound.netty4; +import io.github.kimmking.gateway.router.MyFirstHttpEndpointRouter; import io.netty.bootstrap.Bootstrap; import io.netty.channel.*; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; -import io.netty.handler.codec.http.FullHttpRequest; -import io.netty.handler.codec.http.HttpHeaderNames; -import io.netty.handler.codec.http.HttpRequestEncoder; -import io.netty.handler.codec.http.HttpResponseDecoder; +import io.netty.handler.codec.http.*; + +import java.net.URL; +import java.util.ArrayList; +import java.util.List; public class NettyHttpClient { - private String backendUrl; + private List backendUrlList; - public NettyHttpClient(String backendUrl) { - this.backendUrl = backendUrl; + public NettyHttpClient(List backendUrlList) { + this.backendUrlList = backendUrlList; } public void connect(FullHttpRequest fullHttpRequest, ChannelHandlerContext ctx) throws Exception { + MyFirstHttpEndpointRouter myFirstHttpEndpointRouter = new MyFirstHttpEndpointRouter(); + String backendUrl = myFirstHttpEndpointRouter.route(backendUrlList); + // System.out.println("Current backendUrl: " + backendUrl); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { @@ -47,9 +52,9 @@ public void initChannel(SocketChannel ch) throws Exception { request.headers().set(HttpHeaderNames.CONTENT_LENGTH, request.content().readableBytes());*/ // Start the client. - String host = backendUrl.replaceAll("/", "").split(":")[1]; - String[] split = backendUrl.replaceAll("/", "").split(":"); - int port = split.length < 3 ? 80 : Integer.parseInt(split[2]); + URL url = new URL(backendUrl); + int port = url.getPort() > 0 ? url.getPort() : 80; + String host = url.getHost(); ChannelFuture f = b.connect(host, port).sync(); /*f.channel().write(request); f.channel().flush();*/ @@ -59,9 +64,4 @@ public void initChannel(SocketChannel ch) throws Exception { } } - - public static void main(String[] args) throws Exception { - // NettyHttpClient client = new NettyHttpClient(); - //client.connect("127.0.0.1", 8088); - } } diff --git a/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/netty4/NettyHttpOutboundHandler.java b/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/netty4/NettyHttpOutboundHandler.java index dd411d67..3807ea31 100644 --- a/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/netty4/NettyHttpOutboundHandler.java +++ b/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/netty4/NettyHttpOutboundHandler.java @@ -8,6 +8,7 @@ import io.netty.handler.codec.http.*; import java.net.URI; +import java.net.URL; import static io.netty.handler.codec.http.HttpResponseStatus.NO_CONTENT; import static io.netty.handler.codec.http.HttpResponseStatus.OK; @@ -35,7 +36,7 @@ public void channelActive(ChannelHandlerContext ctx) ctx.writeAndFlush(request);*/ String host = backendUrl.replaceAll("/", "").split(":")[1]; DefaultFullHttpRequest request = new DefaultFullHttpRequest( - HttpVersion.HTTP_1_1, fullHttpRequest.method(), fullHttpRequest.uri()); + HttpVersion.HTTP_1_1, fullHttpRequest.method(), new URI(backendUrl).toASCIIString()); /*DefaultFullHttpRequest request = new DefaultFullHttpRequest( HttpVersion.HTTP_1_1, HttpMethod.GET, new URI("/").toASCIIString());*/ diff --git a/02nio/nio02/src/main/java/io/github/kimmking/gateway/router/MyFirstHttpEndpointRouter.java b/02nio/nio02/src/main/java/io/github/kimmking/gateway/router/MyFirstHttpEndpointRouter.java new file mode 100644 index 00000000..07c6bbd8 --- /dev/null +++ b/02nio/nio02/src/main/java/io/github/kimmking/gateway/router/MyFirstHttpEndpointRouter.java @@ -0,0 +1,31 @@ +package io.github.kimmking.gateway.router; + +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; +import java.util.List; +import java.util.Random; + +public class MyFirstHttpEndpointRouter implements HttpEndpointRouter{ + + @Override + public String route(List endpoints) { + int size = endpoints.size(); + return endpoints.get(new Random().nextInt(size)); + } + + public static void main(String[] args) { + URL url = null; + try { + url = new URL("http://localhost:8088/api/hello"); + URI uri = url.toURI(); + System.out.println(uri.toASCIIString()); + } catch (MalformedURLException e) { + e.printStackTrace(); + } catch (URISyntaxException e) { + e.printStackTrace(); + } + + } +} From 2f9748ff3ac8dd22f94c5be35074e035c09dde38 Mon Sep 17 00:00:00 2001 From: hiram <1104712460@qq.com> Date: Mon, 2 Nov 2020 15:40:44 +0800 Subject: [PATCH 6/7] =?UTF-8?q?=E8=B0=83=E6=95=B4=E4=B8=8B=E6=A0=BC?= =?UTF-8?q?=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../gateway/inbound/HttpInboundServer.java | 4 ++-- .../gateway/outbound/netty4/NettyHttpClient.java | 2 +- .../netty4/NettyHttpOutboundHandler.java | 16 +++++++++------- .../router/MyFirstHttpEndpointRouter.java | 2 +- 4 files changed, 13 insertions(+), 11 deletions(-) diff --git a/02nio/nio02/src/main/java/io/github/kimmking/gateway/inbound/HttpInboundServer.java b/02nio/nio02/src/main/java/io/github/kimmking/gateway/inbound/HttpInboundServer.java index 361568d0..2ec18cc7 100644 --- a/02nio/nio02/src/main/java/io/github/kimmking/gateway/inbound/HttpInboundServer.java +++ b/02nio/nio02/src/main/java/io/github/kimmking/gateway/inbound/HttpInboundServer.java @@ -20,11 +20,11 @@ public class HttpInboundServer { private static Logger logger = LoggerFactory.getLogger(HttpInboundServer.class); private int port; - + private List proxyServerList; public HttpInboundServer(int port, List proxyServerList) { - this.port=port; + this.port = port; this.proxyServerList = proxyServerList; } 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 55a224ca..10f3aa1f 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 @@ -30,7 +30,7 @@ public void connect(FullHttpRequest fullHttpRequest, ChannelHandlerContext ctx) b.group(workerGroup); b.channel(NioSocketChannel.class); b.option(ChannelOption.SO_KEEPALIVE, true) - .option(ChannelOption.SO_RCVBUF, 32 * 1024); + .option(ChannelOption.SO_RCVBUF, 32 * 1024); b.handler(new ChannelInitializer() { @Override public void initChannel(SocketChannel ch) throws Exception { diff --git a/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/netty4/NettyHttpOutboundHandler.java b/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/netty4/NettyHttpOutboundHandler.java index 3807ea31..e96cb201 100644 --- a/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/netty4/NettyHttpOutboundHandler.java +++ b/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/netty4/NettyHttpOutboundHandler.java @@ -20,11 +20,13 @@ public class NettyHttpOutboundHandler extends ChannelInboundHandlerAdapter { private int contentLength = 0; private FullHttpRequest fullHttpRequest = null; private String backendUrl; + public NettyHttpOutboundHandler(ChannelHandlerContext ctx, FullHttpRequest fullHttpRequest, String backendUrl) { this.parentCtx = ctx; this.fullHttpRequest = fullHttpRequest; this.backendUrl = backendUrl; } + @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { @@ -40,15 +42,15 @@ public void channelActive(ChannelHandlerContext ctx) /*DefaultFullHttpRequest request = new DefaultFullHttpRequest( HttpVersion.HTTP_1_1, HttpMethod.GET, new URI("/").toASCIIString());*/ - // 构建http请求 - request.headers().set(HttpHeaderNames.HOST, host); - request.headers().set(HttpHeaderNames.CONNECTION, - HttpHeaderNames.CONNECTION); - request.headers().set(HttpHeaderNames.CONTENT_LENGTH, - request.content().readableBytes()); + // 构建http请求 + request.headers().set(HttpHeaderNames.HOST, host); + request.headers().set(HttpHeaderNames.CONNECTION, + HttpHeaderNames.CONNECTION); + request.headers().set(HttpHeaderNames.CONTENT_LENGTH, + request.content().readableBytes()); ctx.writeAndFlush(request); } - + @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { diff --git a/02nio/nio02/src/main/java/io/github/kimmking/gateway/router/MyFirstHttpEndpointRouter.java b/02nio/nio02/src/main/java/io/github/kimmking/gateway/router/MyFirstHttpEndpointRouter.java index 07c6bbd8..c5b6af33 100644 --- a/02nio/nio02/src/main/java/io/github/kimmking/gateway/router/MyFirstHttpEndpointRouter.java +++ b/02nio/nio02/src/main/java/io/github/kimmking/gateway/router/MyFirstHttpEndpointRouter.java @@ -7,7 +7,7 @@ import java.util.List; import java.util.Random; -public class MyFirstHttpEndpointRouter implements HttpEndpointRouter{ +public class MyFirstHttpEndpointRouter implements HttpEndpointRouter { @Override public String route(List endpoints) { From bf7ef4598268874b11c4c72d93bc48693815a53c Mon Sep 17 00:00:00 2001 From: hiram <1104712460@qq.com> Date: Tue, 3 Nov 2020 17:26:00 +0800 Subject: [PATCH 7/7] =?UTF-8?q?=E8=B0=83=E6=95=B4filter=E5=8A=9F=E8=83=BD?= =?UTF-8?q?=EF=BC=8C=E8=AF=B7=E6=B1=82=E5=90=8E=E5=8F=B0=E6=9C=8D=E5=8A=A1?= =?UTF-8?q?=E7=9A=84=E6=97=B6=E5=80=99=E5=B8=A6=E4=B8=8Aheader=3D=EF=BC=88?= =?UTF-8?q?nio=EF=BC=8C=E5=90=8D=E5=AD=97=EF=BC=89=E7=9A=84=E5=8A=9F?= =?UTF-8?q?=E8=83=BD=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../filter/HttpHeaderRequestFilter.java | 25 +++++++++++ .../filter/HttpMethodRequestFilter.java | 43 ------------------- .../gateway/filter/UriHttpRequestFilter.java | 23 ---------- .../gateway/inbound/HttpInboundHandler.java | 8 +--- .../netty4/NettyHttpOutboundHandler.java | 1 + 5 files changed, 28 insertions(+), 72 deletions(-) create mode 100644 02nio/nio02/src/main/java/io/github/kimmking/gateway/filter/HttpHeaderRequestFilter.java delete mode 100644 02nio/nio02/src/main/java/io/github/kimmking/gateway/filter/HttpMethodRequestFilter.java delete mode 100644 02nio/nio02/src/main/java/io/github/kimmking/gateway/filter/UriHttpRequestFilter.java diff --git a/02nio/nio02/src/main/java/io/github/kimmking/gateway/filter/HttpHeaderRequestFilter.java b/02nio/nio02/src/main/java/io/github/kimmking/gateway/filter/HttpHeaderRequestFilter.java new file mode 100644 index 00000000..1e1e6345 --- /dev/null +++ b/02nio/nio02/src/main/java/io/github/kimmking/gateway/filter/HttpHeaderRequestFilter.java @@ -0,0 +1,25 @@ +package io.github.kimmking.gateway.filter; + +import io.netty.buffer.Unpooled; +import io.netty.channel.ChannelFutureListener; +import io.netty.channel.ChannelHandlerContext; +import io.netty.handler.codec.http.*; + +import java.io.UnsupportedEncodingException; + +import static io.netty.handler.codec.http.HttpResponseStatus.*; +import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1; + + +/** + * 过滤http请求,如果是Post就返回错误信息,get请求就通过 + */ +public class HttpHeaderRequestFilter implements HttpRequestFilter { + + @Override + public void filter(FullHttpRequest fullRequest, final ChannelHandlerContext ctx) { + HttpMethod method = fullRequest.method(); + HttpHeaders headers = fullRequest.headers(); + headers.add("nio", "huangjian"); + } +} diff --git a/02nio/nio02/src/main/java/io/github/kimmking/gateway/filter/HttpMethodRequestFilter.java b/02nio/nio02/src/main/java/io/github/kimmking/gateway/filter/HttpMethodRequestFilter.java deleted file mode 100644 index c9d025c1..00000000 --- a/02nio/nio02/src/main/java/io/github/kimmking/gateway/filter/HttpMethodRequestFilter.java +++ /dev/null @@ -1,43 +0,0 @@ -package io.github.kimmking.gateway.filter; - -import io.netty.buffer.Unpooled; -import io.netty.channel.ChannelFutureListener; -import io.netty.channel.ChannelHandlerContext; -import io.netty.handler.codec.http.*; - -import java.io.UnsupportedEncodingException; - -import static io.netty.handler.codec.http.HttpResponseStatus.*; -import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1; - - -/** - * 过滤http请求,如果是Post就返回错误信息,get请求就通过 - */ -public class HttpMethodRequestFilter implements HttpRequestFilter { - - @Override - public void filter(final FullHttpRequest fullRequest, final ChannelHandlerContext ctx) { - HttpMethod method = fullRequest.method(); - if (method.equals(HttpMethod.POST)) { - FullHttpResponse response = null; - try { - response = new DefaultFullHttpResponse(HTTP_1_1, METHOD_NOT_ALLOWED); - } catch (Exception e) { - e.printStackTrace(); - 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); - } - } - ctx.flush(); - ctx.close(); - } - } - } -} diff --git a/02nio/nio02/src/main/java/io/github/kimmking/gateway/filter/UriHttpRequestFilter.java b/02nio/nio02/src/main/java/io/github/kimmking/gateway/filter/UriHttpRequestFilter.java deleted file mode 100644 index eb0efe42..00000000 --- a/02nio/nio02/src/main/java/io/github/kimmking/gateway/filter/UriHttpRequestFilter.java +++ /dev/null @@ -1,23 +0,0 @@ -package io.github.kimmking.gateway.filter; - -import io.netty.channel.ChannelHandlerContext; -import io.netty.handler.codec.http.DefaultFullHttpResponse; -import io.netty.handler.codec.http.FullHttpRequest; - -import static io.netty.handler.codec.http.HttpResponseStatus.NOT_FOUND; -import static io.netty.handler.codec.http.HttpResponseStatus.NO_CONTENT; -import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1; - -public class UriHttpRequestFilter implements HttpRequestFilter{ - @Override - public void filter(final FullHttpRequest fullRequest, ChannelHandlerContext ctx) { - String uri = fullRequest.uri(); - System.out.println("uri: " + uri); - if (!uri.contains("api/hello")) { - DefaultFullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND); - ctx.write(response); - ctx.flush(); - ctx.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 df0f5652..853e5b6b 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,11 +1,7 @@ package io.github.kimmking.gateway.inbound; -import io.github.kimmking.gateway.filter.HttpMethodRequestFilter; -import io.github.kimmking.gateway.filter.UriHttpRequestFilter; -import io.github.kimmking.gateway.outbound.httpclient4.HttpOutboundHandler; +import io.github.kimmking.gateway.filter.HttpHeaderRequestFilter; import io.github.kimmking.gateway.outbound.netty4.NettyHttpClient; -import io.github.kimmking.gateway.outbound.netty4.NettyHttpOutboundHandler; -import io.github.kimmking.gateway.util.ByteBufToBytes; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.handler.codec.http.*; @@ -44,7 +40,7 @@ public void channelRead(ChannelHandlerContext ctx, Object msg) { // } //handler.handle(fullRequest, ctx); - HttpMethodRequestFilter methodHttpRequestFilter = new HttpMethodRequestFilter(); + HttpHeaderRequestFilter methodHttpRequestFilter = new HttpHeaderRequestFilter(); methodHttpRequestFilter.filter(fullRequest, ctx); // UriHttpRequestFilter uriHttpRequestFilter = new UriHttpRequestFilter(); // uriHttpRequestFilter.filter(fullRequest, ctx); diff --git a/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/netty4/NettyHttpOutboundHandler.java b/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/netty4/NettyHttpOutboundHandler.java index e96cb201..814b41da 100644 --- a/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/netty4/NettyHttpOutboundHandler.java +++ b/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/netty4/NettyHttpOutboundHandler.java @@ -44,6 +44,7 @@ public void channelActive(ChannelHandlerContext ctx) // 构建http请求 request.headers().set(HttpHeaderNames.HOST, host); + request.headers().set("nio", fullHttpRequest.headers().get("nio")); request.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderNames.CONNECTION); request.headers().set(HttpHeaderNames.CONTENT_LENGTH,