Skip to content

Commit 48d0adf

Browse files
committed
update
1 parent c093c37 commit 48d0adf

File tree

9 files changed

+288
-16
lines changed

9 files changed

+288
-16
lines changed

.gitignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,3 +21,5 @@
2121

2222
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
2323
hs_err_pid*
24+
*.iml
25+
*.idea/

02nio/nio02/README.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
# netty-gateway
2+
3+
```
4+
5+
6+
```

02nio/nio02/pom.xml

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4+
<modelVersion>4.0.0</modelVersion>
5+
6+
<groupId>io.github.kimmking</groupId>
7+
<artifactId>netty-gateway</artifactId>
8+
<version>0.0.1-SNAPSHOT</version>
9+
<packaging>jar</packaging>
10+
11+
<name>netty-gateway</name>
12+
<description>Demo project for Spring Boot</description>
13+
14+
<parent>
15+
<groupId>org.springframework.boot</groupId>
16+
<artifactId>spring-boot-starter-parent</artifactId>
17+
<version>2.0.4.RELEASE</version>
18+
<relativePath/>
19+
</parent>
20+
21+
<properties>
22+
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
23+
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
24+
<java.version>1.8</java.version>
25+
</properties>
26+
27+
<dependencies>
28+
29+
<dependency>
30+
<groupId>io.netty</groupId>
31+
<artifactId>netty-all</artifactId>
32+
<version>4.1.45.Final</version>
33+
</dependency>
34+
35+
<dependency>
36+
<groupId>commons-logging</groupId>
37+
<artifactId>commons-logging</artifactId>
38+
<version>1.2</version>
39+
</dependency>
40+
<dependency>
41+
<groupId>org.slf4j</groupId>
42+
<artifactId>slf4j-api</artifactId>
43+
<version>1.7.25</version>
44+
</dependency>
45+
<dependency>
46+
<groupId>org.slf4j</groupId>
47+
<artifactId>slf4j-log4j12</artifactId>
48+
<version>1.7.25</version>
49+
</dependency>
50+
<dependency>
51+
<groupId>org.apache.httpcomponents</groupId>
52+
<artifactId>httpasyncclient</artifactId>
53+
<version>4.1.4</version>
54+
</dependency>
55+
56+
<!--
57+
<dependency>
58+
<groupId>org.springframework.boot</groupId>
59+
<artifactId>spring-boot-starter-web</artifactId>
60+
</dependency>
61+
62+
<dependency>
63+
<groupId>org.springframework.boot</groupId>
64+
<artifactId>spring-boot-starter-test</artifactId>
65+
<scope>test</scope>
66+
</dependency>
67+
-->
68+
69+
</dependencies>
70+
71+
<build>
72+
<plugins>
73+
<plugin>
74+
<groupId>org.springframework.boot</groupId>
75+
<artifactId>spring-boot-maven-plugin</artifactId>
76+
</plugin>
77+
</plugins>
78+
</build>
79+
80+
81+
</project>
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package io.github.kimmking.gateway;
2+
3+
4+
import io.github.kimmking.gateway.inbound.HttpInboundServer;
5+
6+
public class NettyServerApplication {
7+
8+
public final static String GATEWAY_NAME = "NIOGateway";
9+
public final static String GATEWAY_VERSION = "1.0.0";
10+
11+
public static void main(String[] args) {
12+
String proxyServer = System.getProperty("proxyServer","http://localhost:8088");
13+
String proxyPort = System.getProperty("proxyPort","8888");
14+
15+
// http://localhost:8888/api/hello ==> gateway API
16+
// http://localhost:8088/api/hello ==> backend service
17+
18+
int port = Integer.parseInt(proxyPort);
19+
System.out.println(GATEWAY_NAME + " " + GATEWAY_VERSION +" starting...");
20+
HttpInboundServer server = new HttpInboundServer(port, proxyServer);
21+
System.out.println(GATEWAY_NAME + " " + GATEWAY_VERSION +" started at http://localhost:" + port + " for server:" + proxyServer);
22+
try {
23+
server.run();
24+
}catch (Exception ex){
25+
ex.printStackTrace();
26+
}
27+
}
28+
}
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
package io.github.kimmking.gateway.inbound;
2+
3+
import io.github.kimmking.gateway.outbound.httpclient4.HttpOutboundHandler;
4+
import io.netty.channel.ChannelHandlerContext;
5+
import io.netty.channel.ChannelInboundHandlerAdapter;
6+
import io.netty.handler.codec.http.FullHttpRequest;
7+
import io.netty.util.ReferenceCountUtil;
8+
import org.slf4j.Logger;
9+
import org.slf4j.LoggerFactory;
10+
11+
public class HttpInboundHandler extends ChannelInboundHandlerAdapter {
12+
13+
private static Logger logger = LoggerFactory.getLogger(HttpInboundHandler.class);
14+
private final String proxyServer;
15+
private HttpOutboundHandler handler;
16+
17+
public HttpInboundHandler(String proxyServer) {
18+
this.proxyServer = proxyServer;
19+
handler = new HttpOutboundHandler(this.proxyServer);
20+
}
21+
22+
@Override
23+
public void channelReadComplete(ChannelHandlerContext ctx) {
24+
ctx.flush();
25+
}
26+
27+
@Override
28+
public void channelRead(ChannelHandlerContext ctx, Object msg) {
29+
try {
30+
//logger.info("channelRead流量接口请求开始,时间为{}", startTime);
31+
FullHttpRequest fullRequest = (FullHttpRequest) msg;
32+
// String uri = fullRequest.uri();
33+
// //logger.info("接收到的请求url为{}", uri);
34+
// if (uri.contains("/test")) {
35+
// handlerTest(fullRequest, ctx);
36+
// }
37+
38+
handler.handle(fullRequest, ctx);
39+
40+
} catch(Exception e) {
41+
e.printStackTrace();
42+
} finally {
43+
ReferenceCountUtil.release(msg);
44+
}
45+
}
46+
47+
// private void handlerTest(FullHttpRequest fullRequest, ChannelHandlerContext ctx) {
48+
// FullHttpResponse response = null;
49+
// try {
50+
// String value = "hello,kimmking";
51+
// response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(value.getBytes("UTF-8")));
52+
// response.headers().set("Content-Type", "application/json");
53+
// response.headers().setInt("Content-Length", response.content().readableBytes());
54+
//
55+
// } catch (Exception e) {
56+
// logger.error("处理测试接口出错", e);
57+
// response = new DefaultFullHttpResponse(HTTP_1_1, NO_CONTENT);
58+
// } finally {
59+
// if (fullRequest != null) {
60+
// if (!HttpUtil.isKeepAlive(fullRequest)) {
61+
// ctx.write(response).addListener(ChannelFutureListener.CLOSE);
62+
// } else {
63+
// response.headers().set(CONNECTION, KEEP_ALIVE);
64+
// ctx.write(response);
65+
// }
66+
// }
67+
// }
68+
// }
69+
//
70+
// @Override
71+
// public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
72+
// cause.printStackTrace();
73+
// ctx.close();
74+
// }
75+
76+
}
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package io.github.kimmking.gateway.inbound;
2+
3+
import io.netty.channel.ChannelInitializer;
4+
import io.netty.channel.ChannelPipeline;
5+
import io.netty.channel.socket.SocketChannel;
6+
import io.netty.handler.codec.http.HttpObjectAggregator;
7+
import io.netty.handler.codec.http.HttpServerCodec;
8+
9+
public class HttpInboundInitializer extends ChannelInitializer<SocketChannel> {
10+
11+
private String proxyServer;
12+
13+
public HttpInboundInitializer(String proxyServer) {
14+
this.proxyServer = proxyServer;
15+
}
16+
17+
@Override
18+
public void initChannel(SocketChannel ch) {
19+
ChannelPipeline p = ch.pipeline();
20+
// if (sslCtx != null) {
21+
// p.addLast(sslCtx.newHandler(ch.alloc()));
22+
// }
23+
p.addLast(new HttpServerCodec());
24+
//p.addLast(new HttpServerExpectContinueHandler());
25+
p.addLast(new HttpObjectAggregator(1024 * 1024));
26+
p.addLast(new HttpInboundHandler(this.proxyServer));
27+
}
28+
}
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
package io.github.kimmking.gateway.inbound;
2+
3+
import io.netty.bootstrap.ServerBootstrap;
4+
import io.netty.buffer.PooledByteBufAllocator;
5+
import io.netty.channel.Channel;
6+
import io.netty.channel.ChannelOption;
7+
import io.netty.channel.EventLoopGroup;
8+
import io.netty.channel.epoll.EpollChannelOption;
9+
import io.netty.channel.nio.NioEventLoopGroup;
10+
import io.netty.channel.socket.nio.NioServerSocketChannel;
11+
import io.netty.handler.logging.LogLevel;
12+
import io.netty.handler.logging.LoggingHandler;
13+
import org.slf4j.Logger;
14+
import org.slf4j.LoggerFactory;
15+
16+
17+
public class HttpInboundServer {
18+
private static Logger logger = LoggerFactory.getLogger(HttpInboundServer.class);
19+
20+
private int port;
21+
22+
private String proxyServer;
23+
24+
public HttpInboundServer(int port, String proxyServer) {
25+
this.port=port;
26+
this.proxyServer = proxyServer;
27+
}
28+
29+
public void run() throws Exception {
30+
31+
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
32+
EventLoopGroup workerGroup = new NioEventLoopGroup(16);
33+
34+
try {
35+
ServerBootstrap b = new ServerBootstrap();
36+
b.option(ChannelOption.SO_BACKLOG, 128)
37+
.option(ChannelOption.TCP_NODELAY, true)
38+
.option(ChannelOption.SO_KEEPALIVE, true)
39+
.option(ChannelOption.SO_REUSEADDR, true)
40+
.option(ChannelOption.SO_RCVBUF, 32 * 1024)
41+
.option(ChannelOption.SO_SNDBUF, 32 * 1024)
42+
.option(EpollChannelOption.SO_REUSEPORT, true)
43+
.childOption(ChannelOption.SO_KEEPALIVE, true)
44+
.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
45+
46+
b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
47+
.handler(new LoggingHandler(LogLevel.INFO)).childHandler(new HttpInboundInitializer(this.proxyServer));
48+
49+
Channel ch = b.bind(port).sync().channel();
50+
logger.info("开启netty http服务器,监听地址和端口为 http://127.0.0.1:" + port + '/');
51+
ch.closeFuture().sync();
52+
} finally {
53+
bossGroup.shutdownGracefully();
54+
workerGroup.shutdownGracefully();
55+
}
56+
}
57+
}

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

Lines changed: 6 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
//public class NettyHttpClient {
1515
// public void connect(String host, int port) throws Exception {
1616
// EventLoopGroup workerGroup = new NioEventLoopGroup();
17-
//
17+
//
1818
// try {
1919
// Bootstrap b = new Bootstrap();
2020
// b.group(workerGroup);
@@ -30,30 +30,20 @@
3030
// ch.pipeline().addLast(new HttpClientOutboundHandler());
3131
// }
3232
// });
33-
//
33+
//
3434
// // Start the client.
3535
// ChannelFuture f = b.connect(host, port).sync();
36-
//
37-
// // for test
38-
// URI uri = new URI("http://127.0.0.1:8844");
39-
// String msg = "Are you ok?";
40-
// DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET,
41-
// uri.toASCIIString(), Unpooled.wrappedBuffer(msg.getBytes("UTF-8")));
42-
//
43-
// // 构建http请求
44-
// request.headers().set(HttpHeaders.Names.HOST, host);
45-
// request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
46-
// request.headers().set(HttpHeaders.Names.CONTENT_LENGTH, request.content().readableBytes());
47-
// // 发送http请求
36+
//
37+
//
4838
// f.channel().write(request);
4939
// f.channel().flush();
5040
// f.channel().closeFuture().sync();
5141
// } finally {
5242
// workerGroup.shutdownGracefully();
5343
// }
54-
//
44+
//
5545
// }
56-
//
46+
//
5747
// public static void main(String[] args) throws Exception {
5848
// NettyHttpClient client = new NettyHttpClient();
5949
// client.connect("127.0.0.1", 8844);
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
package io.github.kimmking.gateway.outbound.okhttp;
2+
3+
public class OkhttpOutboundHandler {
4+
}

0 commit comments

Comments
 (0)