Skip to content

Commit fdbdc16

Browse files
author
wangyibing
committed
Merge branch 'master' into main
# Conflicts: # 01jvm/GCLogAnalysis.java # 01jvm/环境准备.txt # 02nio/nio01/src/main/java/java0/nio01/HttpServer02.java # 02nio/nio01/src/main/java/java0/nio01/HttpServer03.java # 02nio/nio02/pom.xml # 02nio/nio02/src/main/java/io/github/kimmking/gateway/NettyServerApplication.java # 02nio/nio02/src/main/java/io/github/kimmking/gateway/filter/HttpRequestFilter.java # 02nio/nio02/src/main/java/io/github/kimmking/gateway/inbound/HttpInboundHandler.java # 02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/netty4/NettyHttpClientOutboundHandler.java # 02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/okhttp/OkhttpOutboundHandler.java
2 parents 48d0adf + b2567ad commit fdbdc16

File tree

9 files changed

+163
-14
lines changed

9 files changed

+163
-14
lines changed

02nio/nio01/src/main/java/java0/nio01/HttpServer02.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77

88
public class HttpServer02 {
99
public static void main(String[] args) throws IOException{
10-
ServerSocket serverSocket = new ServerSocket(8802);
10+
ServerSocket serverSocket = new ServerSocket(8089);
1111
while (true) {
1212
try {
1313
final Socket socket = serverSocket.accept();

02nio/nio01/src/main/java/java0/nio01/HttpServer03.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
public class HttpServer03 {
1111
public static void main(String[] args) throws IOException{
1212
ExecutorService executorService = Executors.newFixedThreadPool(40);
13-
final ServerSocket serverSocket = new ServerSocket(8803);
13+
final ServerSocket serverSocket = new ServerSocket(8089);
1414
while (true) {
1515
try {
1616
final Socket socket = serverSocket.accept();

02nio/nio02/pom.xml

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,12 @@
5252
<artifactId>httpasyncclient</artifactId>
5353
<version>4.1.4</version>
5454
</dependency>
55-
55+
56+
<dependency>
57+
<groupId>com.squareup.okhttp3</groupId>
58+
<artifactId>okhttp</artifactId>
59+
<version>3.6.0</version>
60+
</dependency>
5661
<!--
5762
<dependency>
5863
<groupId>org.springframework.boot</groupId>

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,8 @@ public class NettyServerApplication {
99
public final static String GATEWAY_VERSION = "1.0.0";
1010

1111
public static void main(String[] args) {
12-
String proxyServer = System.getProperty("proxyServer","http://localhost:8088");
13-
String proxyPort = System.getProperty("proxyPort","8888");
12+
String proxyServer = System.getProperty("proxyServer","http://localhost:8089");
13+
String proxyPort = System.getProperty("proxyPort","7000");
1414

1515
// http://localhost:8888/api/hello ==> gateway API
1616
// http://localhost:8088/api/hello ==> backend service

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,5 +6,5 @@
66
public interface HttpRequestFilter {
77

88
void filter(FullHttpRequest fullRequest, ChannelHandlerContext ctx);
9-
9+
1010
}

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

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

3-
import io.github.kimmking.gateway.outbound.httpclient4.HttpOutboundHandler;
3+
import io.github.kimmking.gateway.outbound.okhttp.OkhttpOutboundHandler;
44
import io.netty.channel.ChannelHandlerContext;
55
import io.netty.channel.ChannelInboundHandlerAdapter;
66
import io.netty.handler.codec.http.FullHttpRequest;
@@ -12,11 +12,13 @@ public class HttpInboundHandler extends ChannelInboundHandlerAdapter {
1212

1313
private static Logger logger = LoggerFactory.getLogger(HttpInboundHandler.class);
1414
private final String proxyServer;
15-
private HttpOutboundHandler handler;
15+
// private HttpOutboundHandler handler;
16+
private OkhttpOutboundHandler handler;
1617

1718
public HttpInboundHandler(String proxyServer) {
1819
this.proxyServer = proxyServer;
19-
handler = new HttpOutboundHandler(this.proxyServer);
20+
handler = new OkhttpOutboundHandler(proxyServer);
21+
// handler = new HttpOutboundHandler(this.proxyServer);
2022
}
2123

2224
@Override
@@ -34,8 +36,8 @@ public void channelRead(ChannelHandlerContext ctx, Object msg) {
3436
// if (uri.contains("/test")) {
3537
// handlerTest(fullRequest, ctx);
3638
// }
37-
38-
handler.handle(fullRequest, ctx);
39+
40+
handler.handle(fullRequest,ctx);
3941

4042
} catch(Exception e) {
4143
e.printStackTrace();

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

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,14 @@
11
package io.github.kimmking.gateway.outbound.netty4;
22

3+
import io.netty.buffer.Unpooled;
34
import io.netty.channel.ChannelHandlerContext;
45
import io.netty.channel.ChannelInboundHandlerAdapter;
6+
import io.netty.handler.codec.http.DefaultFullHttpResponse;
7+
import io.netty.handler.codec.http.FullHttpResponse;
8+
import io.netty.handler.codec.http.HttpResponse;
9+
10+
import static io.netty.handler.codec.http.HttpResponseStatus.OK;
11+
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;
512

613
public class NettyHttpClientOutboundHandler extends ChannelInboundHandlerAdapter {
714

@@ -15,8 +22,9 @@ public void channelActive(ChannelHandlerContext ctx)
1522
@Override
1623
public void channelRead(ChannelHandlerContext ctx, Object msg)
1724
throws Exception {
18-
19-
20-
25+
26+
HttpResponse response = (HttpResponse) msg;
27+
ctx.writeAndFlush(response);
28+
ctx.channel().closeFuture().sync();
2129
}
2230
}
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
package io.github.kimmking.gateway.outbound.netty4;
2+
3+
import io.netty.bootstrap.Bootstrap;
4+
import io.netty.channel.ChannelFuture;
5+
import io.netty.channel.ChannelInitializer;
6+
import io.netty.channel.ChannelPipeline;
7+
import io.netty.channel.nio.NioEventLoopGroup;
8+
import io.netty.channel.socket.SocketChannel;
9+
import io.netty.channel.socket.nio.NioSocketChannel;
10+
import io.netty.handler.codec.http.DefaultFullHttpRequest;
11+
import io.netty.handler.codec.http.FullHttpRequest;
12+
import io.netty.handler.codec.http.HttpRequestEncoder;
13+
import io.netty.handler.codec.http.HttpResponseDecoder;
14+
15+
public class NettyOutboundServer {
16+
17+
private String proxyServer;
18+
19+
public NettyOutboundServer(String proxyServer) {
20+
this.proxyServer = proxyServer;
21+
}
22+
23+
public void connect(FullHttpRequest httpRequest) throws InterruptedException {
24+
NioEventLoopGroup group = new NioEventLoopGroup();
25+
try {
26+
Bootstrap bootstrap = new Bootstrap();
27+
bootstrap.group(group)
28+
.channel(NioSocketChannel.class)
29+
.handler(new ChannelInitializer<SocketChannel>() {
30+
@Override
31+
protected void initChannel(SocketChannel ch) throws Exception {
32+
ChannelPipeline pipeline = ch.pipeline();
33+
pipeline.addLast(new HttpResponseDecoder());
34+
pipeline.addLast(new HttpRequestEncoder());
35+
pipeline.addLast(new NettyHttpClientOutboundHandler());
36+
}
37+
});
38+
39+
ChannelFuture f = bootstrap.connect("127.0.0.1", 8888).sync();
40+
httpRequest.setUri(proxyServer);
41+
f.channel().write(httpRequest);
42+
f.channel().flush();
43+
f.channel().closeFuture().sync();
44+
} finally {
45+
group.shutdownGracefully();
46+
}
47+
}
48+
}
Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,90 @@
11
package io.github.kimmking.gateway.outbound.okhttp;
22

3+
import io.netty.buffer.Unpooled;
4+
import io.netty.channel.ChannelFutureListener;
5+
import io.netty.channel.ChannelHandlerContext;
6+
import io.netty.handler.codec.http.DefaultFullHttpResponse;
7+
import io.netty.handler.codec.http.FullHttpRequest;
8+
import io.netty.handler.codec.http.HttpUtil;
9+
import okhttp3.OkHttpClient;
10+
import okhttp3.Request;
11+
import okhttp3.Response;
12+
13+
import java.io.IOException;
14+
import java.util.concurrent.ArrayBlockingQueue;
15+
import java.util.concurrent.RejectedExecutionHandler;
16+
import java.util.concurrent.ThreadPoolExecutor;
17+
import java.util.concurrent.TimeUnit;
18+
19+
import static io.netty.handler.codec.http.HttpResponseStatus.NO_CONTENT;
20+
import static io.netty.handler.codec.http.HttpResponseStatus.OK;
21+
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;
22+
323
public class OkhttpOutboundHandler {
24+
25+
private String proxyServer;
26+
27+
private OkHttpClient client;
28+
29+
private ThreadPoolExecutor executor;
30+
31+
public OkhttpOutboundHandler(String proxyServer) {
32+
this.proxyServer = proxyServer;
33+
client = new OkHttpClient.Builder()
34+
.readTimeout(100, TimeUnit.MILLISECONDS)
35+
.connectTimeout(50, TimeUnit.MILLISECONDS)
36+
.build();
37+
RejectedExecutionHandler policy = new ThreadPoolExecutor.CallerRunsPolicy();
38+
int cores = Runtime.getRuntime().availableProcessors() * 2;
39+
long keepAliveTime = 1000;
40+
int queueSize = 2048;
41+
executor = new ThreadPoolExecutor(cores, cores, keepAliveTime, TimeUnit.MILLISECONDS,
42+
new ArrayBlockingQueue<>(queueSize), policy);
43+
}
44+
45+
public void handle(FullHttpRequest fullRequest, ChannelHandlerContext ctx) {
46+
String url = proxyServer + fullRequest.uri();
47+
executor.submit(() -> execute(ctx, url, fullRequest));
48+
}
49+
50+
private void execute(ChannelHandlerContext ctx, String url, FullHttpRequest fullRequest) {
51+
client = new OkHttpClient.Builder()
52+
.build();
53+
Request request = new Request.Builder().get().url(url).build();
54+
Response response = null;
55+
try {
56+
response = client.newCall(request).execute();
57+
handleResponse(ctx, response, fullRequest);
58+
} catch (IOException e) {
59+
e.printStackTrace();
60+
}
61+
}
62+
63+
private void handleResponse(ChannelHandlerContext ctx, Response response, FullHttpRequest fullRequest) throws IOException {
64+
DefaultFullHttpResponse httpResponse = null;
65+
try {
66+
String body = response.body().string();
67+
httpResponse = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(body.getBytes()));
68+
httpResponse.headers().set("Content-Type", "application/json");
69+
httpResponse.headers().setInt("Content-Length", httpResponse.content().readableBytes());
70+
} catch (Exception e) {
71+
e.printStackTrace();
72+
httpResponse = new DefaultFullHttpResponse(HTTP_1_1, NO_CONTENT);
73+
} finally {
74+
if (!HttpUtil.isKeepAlive(fullRequest)) {
75+
ctx.write(httpResponse).addListener(ChannelFutureListener.CLOSE);
76+
} else {
77+
ctx.write(httpResponse);
78+
}
79+
ctx.flush();
80+
}
81+
82+
}
83+
84+
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
85+
cause.printStackTrace();
86+
ctx.close();
87+
}
88+
89+
490
}

0 commit comments

Comments
 (0)