Skip to content

Commit ac4748d

Browse files
author
hiram
committed
gateway1.0
1 parent 48d0adf commit ac4748d

7 files changed

Lines changed: 190 additions & 78 deletions

File tree

02nio/nio02/src/main/java/io/github/kimmking/gateway/NettyServerApplication.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ public static void main(String[] args) {
2121
System.out.println(GATEWAY_NAME + " " + GATEWAY_VERSION +" started at http://localhost:" + port + " for server:" + proxyServer);
2222
try {
2323
server.run();
24-
}catch (Exception ex){
24+
} catch (Exception ex){
2525
ex.printStackTrace();
2626
}
2727
}

02nio/nio02/src/main/java/io/github/kimmking/gateway/inbound/HttpInboundHandler.java

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
package io.github.kimmking.gateway.inbound;
22

33
import io.github.kimmking.gateway.outbound.httpclient4.HttpOutboundHandler;
4+
import io.github.kimmking.gateway.outbound.netty4.NettyHttpClient;
5+
import io.github.kimmking.gateway.outbound.netty4.NettyHttpOutboundHandler;
46
import io.netty.channel.ChannelHandlerContext;
57
import io.netty.channel.ChannelInboundHandlerAdapter;
68
import io.netty.handler.codec.http.FullHttpRequest;
@@ -12,11 +14,11 @@ public class HttpInboundHandler extends ChannelInboundHandlerAdapter {
1214

1315
private static Logger logger = LoggerFactory.getLogger(HttpInboundHandler.class);
1416
private final String proxyServer;
15-
private HttpOutboundHandler handler;
17+
private NettyHttpClient handler;
1618

1719
public HttpInboundHandler(String proxyServer) {
1820
this.proxyServer = proxyServer;
19-
handler = new HttpOutboundHandler(this.proxyServer);
21+
handler = new NettyHttpClient();
2022
}
2123

2224
@Override
@@ -27,6 +29,7 @@ public void channelReadComplete(ChannelHandlerContext ctx) {
2729
@Override
2830
public void channelRead(ChannelHandlerContext ctx, Object msg) {
2931
try {
32+
3033
//logger.info("channelRead流量接口请求开始,时间为{}", startTime);
3134
FullHttpRequest fullRequest = (FullHttpRequest) msg;
3235
// String uri = fullRequest.uri();
@@ -35,8 +38,10 @@ public void channelRead(ChannelHandlerContext ctx, Object msg) {
3538
// handlerTest(fullRequest, ctx);
3639
// }
3740

38-
handler.handle(fullRequest, ctx);
39-
41+
//handler.handle(fullRequest, ctx);
42+
String host = proxyServer.replaceAll("/", "").split(":")[1];
43+
int port = Integer.parseInt(proxyServer.replaceAll("/", "").split(":")[2]);
44+
handler.connect(host, port, ctx);
4045
} catch(Exception e) {
4146
e.printStackTrace();
4247
} finally {

02nio/nio02/src/main/java/io/github/kimmking/gateway/inbound/HttpInboundServer.java

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,10 +33,12 @@ public void run() throws Exception {
3333

3434
try {
3535
ServerBootstrap b = new ServerBootstrap();
36+
// windows下SO_BACKLOG默认200,linux和mac默认128
3637
b.option(ChannelOption.SO_BACKLOG, 128)
3738
.option(ChannelOption.TCP_NODELAY, true)
3839
.option(ChannelOption.SO_KEEPALIVE, true)
3940
.option(ChannelOption.SO_REUSEADDR, true)
41+
// 默认32 * 1024最为合适
4042
.option(ChannelOption.SO_RCVBUF, 32 * 1024)
4143
.option(ChannelOption.SO_SNDBUF, 32 * 1024)
4244
.option(EpollChannelOption.SO_REUSEPORT, true)
Lines changed: 55 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -1,51 +1,55 @@
1-
//package io.github.kimmking.gateway.outbound;
2-
//
3-
//import io.netty.bootstrap.Bootstrap;
4-
//import io.netty.channel.ChannelFuture;
5-
//import io.netty.channel.ChannelInitializer;
6-
//import io.netty.channel.ChannelOption;
7-
//import io.netty.channel.EventLoopGroup;
8-
//import io.netty.channel.nio.NioEventLoopGroup;
9-
//import io.netty.channel.socket.SocketChannel;
10-
//import io.netty.channel.socket.nio.NioSocketChannel;
11-
//import io.netty.handler.codec.http.HttpRequestEncoder;
12-
//import io.netty.handler.codec.http.HttpResponseDecoder;
13-
//
14-
//public class NettyHttpClient {
15-
// public void connect(String host, int port) throws Exception {
16-
// EventLoopGroup workerGroup = new NioEventLoopGroup();
17-
//
18-
// try {
19-
// Bootstrap b = new Bootstrap();
20-
// b.group(workerGroup);
21-
// b.channel(NioSocketChannel.class);
22-
// b.option(ChannelOption.SO_KEEPALIVE, true);
23-
// b.handler(new ChannelInitializer<SocketChannel>() {
24-
// @Override
25-
// public void initChannel(SocketChannel ch) throws Exception {
26-
// // 客户端接收到的是httpResponse响应,所以要使用HttpResponseDecoder进行解码
27-
// ch.pipeline().addLast(new HttpResponseDecoder());
28-
// 客户端发送的是httprequest,所以要使用HttpRequestEncoder进行编码
29-
// ch.pipeline().addLast(new HttpRequestEncoder());
30-
// ch.pipeline().addLast(new HttpClientOutboundHandler());
31-
// }
32-
// });
33-
//
34-
// // Start the client.
35-
// ChannelFuture f = b.connect(host, port).sync();
36-
//
37-
//
38-
// f.channel().write(request);
39-
// f.channel().flush();
40-
// f.channel().closeFuture().sync();
41-
// } finally {
42-
// workerGroup.shutdownGracefully();
43-
// }
44-
//
45-
// }
46-
//
47-
// public static void main(String[] args) throws Exception {
48-
// NettyHttpClient client = new NettyHttpClient();
49-
// client.connect("127.0.0.1", 8844);
50-
// }
51-
//}
1+
package io.github.kimmking.gateway.outbound.netty4;
2+
3+
import io.netty.bootstrap.Bootstrap;
4+
import io.netty.channel.*;
5+
import io.netty.channel.nio.NioEventLoopGroup;
6+
import io.netty.channel.socket.SocketChannel;
7+
import io.netty.channel.socket.nio.NioSocketChannel;
8+
import io.netty.handler.codec.http.*;
9+
10+
public class NettyHttpClient {
11+
public void connect(String host, int port, ChannelHandlerContext ctx) throws Exception {
12+
EventLoopGroup workerGroup = new NioEventLoopGroup();
13+
14+
try {
15+
Bootstrap b = new Bootstrap();
16+
b.group(workerGroup);
17+
b.channel(NioSocketChannel.class);
18+
b.option(ChannelOption.SO_KEEPALIVE, true)
19+
.option(ChannelOption.SO_RCVBUF, 32 * 1024);
20+
b.handler(new ChannelInitializer<SocketChannel>() {
21+
@Override
22+
public void initChannel(SocketChannel ch) throws Exception {
23+
// 客户端接收到的是httpResponse响应,所以要使用HttpResponseDecoder进行解码
24+
ch.pipeline().addLast(new HttpResponseDecoder());
25+
// 客户端发送的是httprequest,所以要使用HttpRequestEncoder进行编码
26+
ch.pipeline().addLast(new HttpRequestEncoder());
27+
ch.pipeline().addLast(new NettyHttpOutboundHandler(ctx));
28+
}
29+
});
30+
31+
32+
/*DefaultFullHttpRequest request = new DefaultFullHttpRequest(
33+
HttpVersion.HTTP_1_1, HttpMethod.GET, new URI("/api/hello").toASCIIString());
34+
// 构建http请求
35+
request.headers().set(HttpHeaderNames.HOST, host);
36+
request.headers().set(HttpHeaderNames.CONNECTION,
37+
HttpHeaderNames.CONNECTION);
38+
request.headers().set(HttpHeaderNames.CONTENT_LENGTH,
39+
request.content().readableBytes());*/
40+
// Start the client.
41+
ChannelFuture f = b.connect(host, port).sync();
42+
/*f.channel().write(request);
43+
f.channel().flush();*/
44+
f.channel().closeFuture().sync();
45+
} finally {
46+
workerGroup.shutdownGracefully();
47+
}
48+
49+
}
50+
51+
public static void main(String[] args) throws Exception {
52+
NettyHttpClient client = new NettyHttpClient();
53+
//client.connect("127.0.0.1", 8088);
54+
}
55+
}

02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/netty4/NettyHttpClientOutboundHandler.java

Lines changed: 0 additions & 22 deletions
This file was deleted.
Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
package io.github.kimmking.gateway.outbound.netty4;
2+
3+
import io.github.kimmking.gateway.util.ByteBufToBytes;
4+
import io.netty.bootstrap.Bootstrap;
5+
import io.netty.buffer.ByteBuf;
6+
import io.netty.buffer.Unpooled;
7+
import io.netty.channel.*;
8+
import io.netty.channel.nio.NioEventLoopGroup;
9+
import io.netty.channel.socket.SocketChannel;
10+
import io.netty.channel.socket.nio.NioSocketChannel;
11+
import io.netty.handler.codec.http.*;
12+
import org.apache.http.util.EntityUtils;
13+
14+
import java.net.URI;
15+
16+
import static io.netty.handler.codec.http.HttpResponseStatus.NO_CONTENT;
17+
import static io.netty.handler.codec.http.HttpResponseStatus.OK;
18+
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;
19+
20+
public class NettyHttpOutboundHandler extends ChannelInboundHandlerAdapter {
21+
private ByteBufToBytes reader;
22+
private ChannelHandlerContext parentCtx;
23+
private int contentLength = 0;
24+
public NettyHttpOutboundHandler(ChannelHandlerContext ctx) {
25+
this.parentCtx = ctx;
26+
}
27+
@Override
28+
public void channelActive(ChannelHandlerContext ctx)
29+
throws Exception {
30+
System.out.println("channelActive");
31+
/* URI uri = new URI("/api/hello");
32+
FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri.toASCIIString());
33+
request.headers().add(HttpHeaderNames.CONNECTION,HttpHeaderValues.KEEP_ALIVE);
34+
request.headers().add(HttpHeaderNames.CONTENT_LENGTH,request.content().readableBytes());
35+
ctx.writeAndFlush(request);*/
36+
DefaultFullHttpRequest request = new DefaultFullHttpRequest(
37+
HttpVersion.HTTP_1_1, HttpMethod.GET, new URI("/api/hello").toASCIIString());
38+
// 构建http请求
39+
request.headers().set(HttpHeaderNames.HOST, "127.0.0.1");
40+
request.headers().set(HttpHeaderNames.CONNECTION,
41+
HttpHeaderNames.CONNECTION);
42+
request.headers().set(HttpHeaderNames.CONTENT_LENGTH,
43+
request.content().readableBytes());
44+
ctx.writeAndFlush(request);
45+
}
46+
47+
@Override
48+
public void channelRead(ChannelHandlerContext ctx, Object msg)
49+
throws Exception {
50+
System.out.println("channelRead");
51+
52+
if (msg instanceof HttpResponse) {
53+
HttpResponse response = (HttpResponse) msg;
54+
System.out.println("CONTENT_TYPE:"
55+
+ response.headers().get(HttpHeaderNames.CONTENT_TYPE));
56+
if (HttpUtil.isContentLengthSet(response)) {
57+
contentLength = (int) HttpUtil.getContentLength(response);
58+
reader = new ByteBufToBytes(contentLength);
59+
}
60+
}
61+
if (msg instanceof HttpContent) {
62+
HttpContent httpContent = (HttpContent) msg;
63+
ByteBuf content = httpContent.content();
64+
reader.reading(content);
65+
content.release();
66+
byte[] bytes = reader.readFull();
67+
System.out.println(new String(bytes));
68+
if (reader.isEnd()) {
69+
FullHttpResponse response = null;
70+
try {
71+
response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(bytes));
72+
response.headers().set("Content-Type", "text/plain;charset=UTF-8");
73+
response.headers().setInt("Content-Length", contentLength);
74+
} catch (Exception e) {
75+
e.printStackTrace();
76+
response = new DefaultFullHttpResponse(HTTP_1_1, NO_CONTENT);
77+
exceptionCaught(parentCtx, e);
78+
} finally {
79+
parentCtx.write(response);
80+
}
81+
parentCtx.flush();
82+
ctx.close();
83+
}
84+
}
85+
}
86+
}
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package io.github.kimmking.gateway.util;
2+
3+
import io.netty.buffer.ByteBuf;
4+
import io.netty.buffer.Unpooled;
5+
public class ByteBufToBytes {
6+
private ByteBuf temp;
7+
private boolean end = true;
8+
public ByteBufToBytes(int length) {
9+
temp = Unpooled.buffer(length);
10+
}
11+
public void reading(ByteBuf datas) {
12+
datas.readBytes(temp, datas.readableBytes());
13+
if (this.temp.writableBytes() != 0) {
14+
end = false;
15+
} else {
16+
end = true;
17+
}
18+
}
19+
public boolean isEnd() {
20+
return end;
21+
}
22+
public byte[] readFull() {
23+
if (end) {
24+
byte[] contentByte = new byte[this.temp.readableBytes()];
25+
this.temp.readBytes(contentByte);
26+
this.temp.release();
27+
return contentByte;
28+
} else {
29+
return null;
30+
}
31+
}
32+
public byte[] read(ByteBuf datas) {
33+
byte[] bytes = new byte[datas.readableBytes()];
34+
datas.readBytes(bytes);
35+
return bytes;
36+
}
37+
}

0 commit comments

Comments
 (0)