Skip to content

Commit 6058224

Browse files
committed
add router for gateway
1 parent dbd14b1 commit 6058224

File tree

10 files changed

+188
-20
lines changed

10 files changed

+188
-20
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
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" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
3+
<modelVersion>4.0.0</modelVersion>
4+
<groupId>java0.nio01</groupId>
5+
<artifactId>nio01</artifactId>
6+
<version>1.0</version>
7+
<build>
8+
<plugins>
9+
<plugin>
10+
<artifactId>maven-compiler-plugin</artifactId>
11+
<configuration>
12+
<source>${maven.compile.source}</source>
13+
<target>${maven.compile.target}</target>
14+
</configuration>
15+
</plugin>
16+
<plugin>
17+
<artifactId>maven-shade-plugin</artifactId>
18+
<version>3.2.0</version>
19+
<executions>
20+
<execution>
21+
<goals>
22+
<goal>shade</goal>
23+
</goals>
24+
<configuration>
25+
<transformers>
26+
<transformer>
27+
<manifestEntries>
28+
<Main-Class>${app.main.class}</Main-Class>
29+
<X-Compile-Source-JDK>${maven.compile.source}</X-Compile-Source-JDK>
30+
<X-Compile-Target-JDK>${maven.compile.target}</X-Compile-Target-JDK>
31+
</manifestEntries>
32+
</transformer>
33+
</transformers>
34+
</configuration>
35+
</execution>
36+
</executions>
37+
</plugin>
38+
</plugins>
39+
</build>
40+
<properties>
41+
<app.main.class>Main</app.main.class>
42+
<maven.compile.source>8</maven.compile.source>
43+
<maven.compile.target>8</maven.compile.target>
44+
</properties>
45+
</project>

02nio/nio01/pom.xml

Lines changed: 35 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,19 +7,52 @@
77
<groupId>java0.nio01</groupId>
88
<artifactId>nio01</artifactId>
99
<version>1.0</version>
10+
11+
<properties>
12+
<app.main.class>Main</app.main.class>
13+
<maven.compile.source>8</maven.compile.source>
14+
<maven.compile.target>8</maven.compile.target>
15+
</properties>
16+
1017
<build>
1118
<plugins>
1219
<plugin>
1320
<groupId>org.apache.maven.plugins</groupId>
1421
<artifactId>maven-compiler-plugin</artifactId>
1522
<configuration>
16-
<source>8</source>
17-
<target>8</target>
23+
<source>${maven.compile.source}</source>
24+
<target>${maven.compile.target}</target>
1825
</configuration>
1926
</plugin>
27+
28+
<plugin>
29+
<groupId>org.apache.maven.plugins</groupId>
30+
<artifactId>maven-shade-plugin</artifactId>
31+
<version>3.2.0</version>
32+
<executions>
33+
<execution>
34+
<goals>
35+
<goal>shade</goal>
36+
</goals>
37+
<configuration>
38+
<transformers>
39+
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
40+
<manifestEntries>
41+
<Main-Class>${app.main.class}</Main-Class>
42+
<X-Compile-Source-JDK>${maven.compile.source}</X-Compile-Source-JDK>
43+
<X-Compile-Target-JDK>${maven.compile.target}</X-Compile-Target-JDK>
44+
</manifestEntries>
45+
</transformer>
46+
</transformers>
47+
</configuration>
48+
</execution>
49+
</executions>
50+
</plugin>
2051
</plugins>
2152
</build>
2253

54+
55+
2356
<dependencies>
2457
<dependency>
2558
<groupId>io.netty</groupId>
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import java0.nio01.HttpServer01;
2+
import java0.nio01.HttpServer02;
3+
import java0.nio01.HttpServer03;
4+
import java0.nio01.netty.NettyHttpServer;
5+
6+
import java.lang.reflect.Method;
7+
import java.util.HashMap;
8+
import java.util.Map;
9+
10+
public class Main {
11+
12+
public static void main(String[] args) {
13+
Map<String, Class> map = new HashMap<>();
14+
map.put("1", HttpServer01.class);
15+
map.put("2", HttpServer02.class);
16+
map.put("3", HttpServer03.class);
17+
map.put("8", NettyHttpServer.class);
18+
19+
String id = (null == args || args.length == 0) ? "1" : args[0];
20+
Class clazz = map.get(id);
21+
if( null == clazz ) {
22+
System.out.println("No class for id: " + id);
23+
}
24+
25+
try {
26+
Method method = clazz.getDeclaredMethod("main", new Class[]{String[].class});
27+
method.invoke(null, new Object[]{new String[]{}});
28+
} catch (Exception e) {
29+
e.printStackTrace();
30+
}
31+
32+
}
33+
34+
}

02nio/nio01/src/main/java/java0/nio01/netty/HttpHandler.java

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,12 @@ public void channelRead(ChannelHandlerContext ctx, Object msg) {
4444
private void handlerTest(FullHttpRequest fullRequest, ChannelHandlerContext ctx) {
4545
FullHttpResponse response = null;
4646
try {
47-
String value = "hello,kimmking";
47+
String value = null; // "hello,kimmking"; // 对接上次作业的httpclient或者okhttp请求另一个url的响应数据
48+
49+
// httpGet ... http://localhost:8801
50+
// 返回的响应,"hello,nio";
51+
// value = reponse....
52+
4853
response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(value.getBytes("UTF-8")));
4954
response.headers().set("Content-Type", "application/json");
5055
response.headers().setInt("Content-Length", response.content().readableBytes());

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

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33

44
import io.github.kimmking.gateway.inbound.HttpInboundServer;
55

6+
import java.util.Arrays;
7+
68
public class NettyServerApplication {
79

810
public final static String GATEWAY_NAME = "NIOGateway";
@@ -17,7 +19,7 @@ public static void main(String[] args) {
1719

1820
int port = Integer.parseInt(proxyPort);
1921
System.out.println(GATEWAY_NAME + " " + GATEWAY_VERSION +" starting...");
20-
HttpInboundServer server = new HttpInboundServer(port, proxyServer);
22+
HttpInboundServer server = new HttpInboundServer(port, Arrays.asList("http://localhost:8081","http://localhost:8082"));
2123
System.out.println(GATEWAY_NAME + " " + GATEWAY_VERSION +" started at http://localhost:" + port + " for server:" + proxyServer);
2224
try {
2325
server.run();

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

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

3+
import io.github.kimmking.gateway.filter.HttpRequestFilter;
34
import io.github.kimmking.gateway.outbound.httpclient4.HttpOutboundHandler;
45
import io.netty.channel.ChannelHandlerContext;
56
import io.netty.channel.ChannelInboundHandlerAdapter;
@@ -8,14 +9,18 @@
89
import org.slf4j.Logger;
910
import org.slf4j.LoggerFactory;
1011

12+
import java.util.List;
13+
1114
public class HttpInboundHandler extends ChannelInboundHandlerAdapter {
1215

1316
private static Logger logger = LoggerFactory.getLogger(HttpInboundHandler.class);
14-
private final String proxyServer;
17+
private final List<String> proxyServer;
1518
private HttpOutboundHandler handler;
19+
private HttpRequestFilter filter;
1620

17-
public HttpInboundHandler(String proxyServer) {
21+
public HttpInboundHandler(List<String> proxyServer, HttpRequestFilter filter) {
1822
this.proxyServer = proxyServer;
23+
this.filter = filter;
1924
handler = new HttpOutboundHandler(this.proxyServer);
2025
}
2126

@@ -35,7 +40,7 @@ public void channelRead(ChannelHandlerContext ctx, Object msg) {
3540
// handlerTest(fullRequest, ctx);
3641
// }
3742

38-
handler.handle(fullRequest, ctx);
43+
handler.handle(fullRequest, ctx, filter);
3944

4045
} catch(Exception e) {
4146
e.printStackTrace();

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

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,21 @@
11
package io.github.kimmking.gateway.inbound;
22

3+
import io.github.kimmking.gateway.filter.HttpRequestFilter;
4+
import io.netty.channel.ChannelHandlerContext;
35
import io.netty.channel.ChannelInitializer;
46
import io.netty.channel.ChannelPipeline;
57
import io.netty.channel.socket.SocketChannel;
8+
import io.netty.handler.codec.http.FullHttpRequest;
69
import io.netty.handler.codec.http.HttpObjectAggregator;
710
import io.netty.handler.codec.http.HttpServerCodec;
811

12+
import java.util.List;
13+
914
public class HttpInboundInitializer extends ChannelInitializer<SocketChannel> {
1015

11-
private String proxyServer;
16+
private List<String> proxyServer;
1217

13-
public HttpInboundInitializer(String proxyServer) {
18+
public HttpInboundInitializer(List<String> proxyServer) {
1419
this.proxyServer = proxyServer;
1520
}
1621

@@ -23,6 +28,11 @@ public void initChannel(SocketChannel ch) {
2328
p.addLast(new HttpServerCodec());
2429
//p.addLast(new HttpServerExpectContinueHandler());
2530
p.addLast(new HttpObjectAggregator(1024 * 1024));
26-
p.addLast(new HttpInboundHandler(this.proxyServer));
31+
p.addLast(new HttpInboundHandler(this.proxyServer, new HttpRequestFilter() {
32+
@Override
33+
public void filter(FullHttpRequest fullRequest, ChannelHandlerContext ctx) {
34+
fullRequest.headers().set("mao", "soul");
35+
}
36+
}));
2737
}
2838
}

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

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,17 +13,19 @@
1313
import org.slf4j.Logger;
1414
import org.slf4j.LoggerFactory;
1515

16+
import java.util.List;
17+
1618

1719
public class HttpInboundServer {
1820
private static Logger logger = LoggerFactory.getLogger(HttpInboundServer.class);
1921

2022
private int port;
2123

22-
private String proxyServer;
24+
private List<String> proxyServers;
2325

24-
public HttpInboundServer(int port, String proxyServer) {
26+
public HttpInboundServer(int port, List<String> proxyServers) {
2527
this.port=port;
26-
this.proxyServer = proxyServer;
28+
this.proxyServers = proxyServers;
2729
}
2830

2931
public void run() throws Exception {
@@ -44,7 +46,7 @@ public void run() throws Exception {
4446
.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
4547

4648
b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
47-
.handler(new LoggingHandler(LogLevel.INFO)).childHandler(new HttpInboundInitializer(this.proxyServer));
49+
.handler(new LoggingHandler(LogLevel.INFO)).childHandler(new HttpInboundInitializer(this.proxyServers));
4850

4951
Channel ch = b.bind(port).sync().channel();
5052
logger.info("开启netty http服务器,监听地址和端口为 http://127.0.0.1:" + port + '/');

02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/httpclient4/HttpOutboundHandler.java

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

33

4+
import io.github.kimmking.gateway.filter.HttpRequestFilter;
5+
import io.github.kimmking.gateway.router.HttpEndpointRouter;
6+
import io.github.kimmking.gateway.router.RandomHttpEndpointRouter;
47
import io.netty.buffer.Unpooled;
58
import io.netty.channel.ChannelFutureListener;
69
import io.netty.channel.ChannelHandlerContext;
@@ -17,7 +20,11 @@
1720
import org.apache.http.protocol.HTTP;
1821
import org.apache.http.util.EntityUtils;
1922

23+
import java.util.List;
24+
import java.util.Random;
2025
import java.util.concurrent.*;
26+
import java.util.logging.Filter;
27+
import java.util.stream.Collectors;
2128

2229
import static io.netty.handler.codec.http.HttpResponseStatus.NO_CONTENT;
2330
import static io.netty.handler.codec.http.HttpResponseStatus.OK;
@@ -27,10 +34,14 @@ public class HttpOutboundHandler {
2734

2835
private CloseableHttpAsyncClient httpclient;
2936
private ExecutorService proxyService;
30-
private String backendUrl;
31-
32-
public HttpOutboundHandler(String backendUrl){
33-
this.backendUrl = backendUrl.endsWith("/")?backendUrl.substring(0,backendUrl.length()-1):backendUrl;
37+
private List<String> backendUrls;
38+
39+
HttpEndpointRouter router = new RandomHttpEndpointRouter();
40+
41+
public HttpOutboundHandler(List<String> backends) {
42+
43+
this.backendUrls = backendUrls.stream().map(this::formatUrl).collect(Collectors.toList());
44+
3445
int cores = Runtime.getRuntime().availableProcessors() * 2;
3546
long keepAliveTime = 1000;
3647
int queueSize = 2048;
@@ -53,16 +64,24 @@ public HttpOutboundHandler(String backendUrl){
5364
.build();
5465
httpclient.start();
5566
}
67+
68+
private String formatUrl(String backend) {
69+
return backend.endsWith("/")?backend.substring(0,backend.length()-1):backend;
70+
}
5671

57-
public void handle(final FullHttpRequest fullRequest, final ChannelHandlerContext ctx) {
58-
final String url = this.backendUrl + fullRequest.uri();
72+
public void handle(final FullHttpRequest fullRequest, final ChannelHandlerContext ctx, HttpRequestFilter filter) {
73+
String backendUrl = router.route(this.backendUrls);
74+
final String url = backendUrl + fullRequest.uri();
75+
filter.filter(fullRequest, ctx);
5976
proxyService.submit(()->fetchGet(fullRequest, ctx, url));
6077
}
6178

6279
private void fetchGet(final FullHttpRequest inbound, final ChannelHandlerContext ctx, final String url) {
6380
final HttpGet httpGet = new HttpGet(url);
6481
//httpGet.setHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE);
6582
httpGet.setHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE);
83+
httpGet.setHeader("mao", inbound.headers().get("mao"));
84+
6685
httpclient.execute(httpGet, new FutureCallback<HttpResponse>() {
6786
@Override
6887
public void completed(final HttpResponse endpointResponse) {
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
package io.github.kimmking.gateway.router;
2+
3+
import java.util.List;
4+
import java.util.Random;
5+
6+
public class RandomHttpEndpointRouter implements HttpEndpointRouter {
7+
@Override
8+
public String route(List<String> urls) {
9+
int size = urls.size();
10+
Random random = new Random(size);
11+
return urls.get(random.nextInt());
12+
}
13+
}

0 commit comments

Comments
 (0)