Skip to content

Commit c4a39a3

Browse files
author
hiram
committed
添加Router
1 parent 33f94b3 commit c4a39a3

7 files changed

Lines changed: 78 additions & 35 deletions

File tree

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

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,23 +3,29 @@
33

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

6+
import java.util.ArrayList;
7+
import java.util.List;
8+
69
public class NettyServerApplication {
710

811
public final static String GATEWAY_NAME = "NIOGateway";
912
public final static String GATEWAY_VERSION = "1.0.0";
1013

1114
public static void main(String[] args) {
12-
String proxyServer = System.getProperty("proxyServer","http://localhost:8088");
13-
//String proxyServer = System.getProperty("proxyServer","http://www.baidu.com");
15+
String proxyServer1 = System.getProperty("proxyServer","http://localhost:8088/api/hello");
16+
String proxyServer2 = System.getProperty("proxyServer","http://www.baidu.com");
17+
ArrayList<String> proxyServerList = new ArrayList<>();
18+
proxyServerList.add(proxyServer1);
19+
proxyServerList.add(proxyServer2);
1420
String proxyPort = System.getProperty("proxyPort","8888");
1521

1622
// http://localhost:8888/api/hello ==> gateway API
1723
// http://localhost:8088/api/hello ==> backend service
1824

1925
int port = Integer.parseInt(proxyPort);
2026
System.out.println(GATEWAY_NAME + " " + GATEWAY_VERSION +" starting...");
21-
HttpInboundServer server = new HttpInboundServer(port, proxyServer);
22-
System.out.println(GATEWAY_NAME + " " + GATEWAY_VERSION +" started at http://localhost:" + port + "/api/hello for server:" + proxyServer + "/api/hello");
27+
HttpInboundServer server = new HttpInboundServer(port, proxyServerList);
28+
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");
2329
try {
2430
server.run();
2531
} catch (Exception ex){

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

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,23 +5,25 @@
55
import io.github.kimmking.gateway.outbound.httpclient4.HttpOutboundHandler;
66
import io.github.kimmking.gateway.outbound.netty4.NettyHttpClient;
77
import io.github.kimmking.gateway.outbound.netty4.NettyHttpOutboundHandler;
8+
import io.github.kimmking.gateway.util.ByteBufToBytes;
89
import io.netty.channel.ChannelHandlerContext;
910
import io.netty.channel.ChannelInboundHandlerAdapter;
10-
import io.netty.handler.codec.http.FullHttpRequest;
11-
import io.netty.handler.codec.http.HttpHeaderNames;
11+
import io.netty.handler.codec.http.*;
1212
import io.netty.util.ReferenceCountUtil;
1313
import org.slf4j.Logger;
1414
import org.slf4j.LoggerFactory;
1515

16+
import java.util.List;
17+
1618
public class HttpInboundHandler extends ChannelInboundHandlerAdapter {
1719

1820
private static Logger logger = LoggerFactory.getLogger(HttpInboundHandler.class);
19-
private final String proxyServer;
21+
private final List<String> proxyServerList;
2022
private NettyHttpClient handler;
2123

22-
public HttpInboundHandler(String proxyServer) {
23-
this.proxyServer = proxyServer;
24-
handler = new NettyHttpClient(proxyServer);
24+
public HttpInboundHandler(List<String> proxyServerList) {
25+
this.proxyServerList = proxyServerList;
26+
handler = new NettyHttpClient(proxyServerList);
2527
}
2628

2729
@Override
@@ -32,7 +34,6 @@ public void channelReadComplete(ChannelHandlerContext ctx) {
3234
@Override
3335
public void channelRead(ChannelHandlerContext ctx, Object msg) {
3436
try {
35-
3637
//logger.info("channelRead流量接口请求开始,时间为{}", startTime);
3738
FullHttpRequest fullRequest = (FullHttpRequest) msg;
3839
String uri = fullRequest.uri();

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

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,14 @@
66
import io.netty.handler.codec.http.HttpObjectAggregator;
77
import io.netty.handler.codec.http.HttpServerCodec;
88

9+
import java.util.List;
10+
911
public class HttpInboundInitializer extends ChannelInitializer<SocketChannel> {
1012

11-
private String proxyServer;
13+
private List<String> proxyServerList;
1214

13-
public HttpInboundInitializer(String proxyServer) {
14-
this.proxyServer = proxyServer;
15+
public HttpInboundInitializer(List<String> proxyServerList) {
16+
this.proxyServerList = proxyServerList;
1517
}
1618

1719
@Override
@@ -23,6 +25,6 @@ public void initChannel(SocketChannel ch) {
2325
p.addLast(new HttpServerCodec());
2426
//p.addLast(new HttpServerExpectContinueHandler());
2527
p.addLast(new HttpObjectAggregator(1024 * 1024));
26-
p.addLast(new HttpInboundHandler(this.proxyServer));
28+
p.addLast(new HttpInboundHandler(this.proxyServerList));
2729
}
2830
}

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> proxyServerList;
2325

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

2931
public void run() throws Exception {
@@ -46,7 +48,7 @@ public void run() throws Exception {
4648
.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
4749

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

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

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

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

3+
import io.github.kimmking.gateway.router.MyFirstHttpEndpointRouter;
34
import io.netty.bootstrap.Bootstrap;
45
import io.netty.channel.*;
56
import io.netty.channel.nio.NioEventLoopGroup;
67
import io.netty.channel.socket.SocketChannel;
78
import io.netty.channel.socket.nio.NioSocketChannel;
8-
import io.netty.handler.codec.http.FullHttpRequest;
9-
import io.netty.handler.codec.http.HttpHeaderNames;
10-
import io.netty.handler.codec.http.HttpRequestEncoder;
11-
import io.netty.handler.codec.http.HttpResponseDecoder;
9+
import io.netty.handler.codec.http.*;
10+
11+
import java.net.URL;
12+
import java.util.ArrayList;
13+
import java.util.List;
1214

1315
public class NettyHttpClient {
14-
private String backendUrl;
16+
private List<String> backendUrlList;
1517

16-
public NettyHttpClient(String backendUrl) {
17-
this.backendUrl = backendUrl;
18+
public NettyHttpClient(List<String> backendUrlList) {
19+
this.backendUrlList = backendUrlList;
1820
}
1921

2022
public void connect(FullHttpRequest fullHttpRequest, ChannelHandlerContext ctx) throws Exception {
23+
MyFirstHttpEndpointRouter myFirstHttpEndpointRouter = new MyFirstHttpEndpointRouter();
24+
String backendUrl = myFirstHttpEndpointRouter.route(backendUrlList);
25+
// System.out.println("Current backendUrl: " + backendUrl);
2126
EventLoopGroup workerGroup = new NioEventLoopGroup();
2227

2328
try {
@@ -47,9 +52,9 @@ public void initChannel(SocketChannel ch) throws Exception {
4752
request.headers().set(HttpHeaderNames.CONTENT_LENGTH,
4853
request.content().readableBytes());*/
4954
// Start the client.
50-
String host = backendUrl.replaceAll("/", "").split(":")[1];
51-
String[] split = backendUrl.replaceAll("/", "").split(":");
52-
int port = split.length < 3 ? 80 : Integer.parseInt(split[2]);
55+
URL url = new URL(backendUrl);
56+
int port = url.getPort() > 0 ? url.getPort() : 80;
57+
String host = url.getHost();
5358
ChannelFuture f = b.connect(host, port).sync();
5459
/*f.channel().write(request);
5560
f.channel().flush();*/
@@ -59,9 +64,4 @@ public void initChannel(SocketChannel ch) throws Exception {
5964
}
6065

6166
}
62-
63-
public static void main(String[] args) throws Exception {
64-
// NettyHttpClient client = new NettyHttpClient();
65-
//client.connect("127.0.0.1", 8088);
66-
}
6767
}

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

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
import io.netty.handler.codec.http.*;
99

1010
import java.net.URI;
11+
import java.net.URL;
1112

1213
import static io.netty.handler.codec.http.HttpResponseStatus.NO_CONTENT;
1314
import static io.netty.handler.codec.http.HttpResponseStatus.OK;
@@ -35,7 +36,7 @@ public void channelActive(ChannelHandlerContext ctx)
3536
ctx.writeAndFlush(request);*/
3637
String host = backendUrl.replaceAll("/", "").split(":")[1];
3738
DefaultFullHttpRequest request = new DefaultFullHttpRequest(
38-
HttpVersion.HTTP_1_1, fullHttpRequest.method(), fullHttpRequest.uri());
39+
HttpVersion.HTTP_1_1, fullHttpRequest.method(), new URI(backendUrl).toASCIIString());
3940
/*DefaultFullHttpRequest request = new DefaultFullHttpRequest(
4041
HttpVersion.HTTP_1_1, HttpMethod.GET, new URI("/").toASCIIString());*/
4142

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package io.github.kimmking.gateway.router;
2+
3+
import java.net.MalformedURLException;
4+
import java.net.URI;
5+
import java.net.URISyntaxException;
6+
import java.net.URL;
7+
import java.util.List;
8+
import java.util.Random;
9+
10+
public class MyFirstHttpEndpointRouter implements HttpEndpointRouter{
11+
12+
@Override
13+
public String route(List<String> endpoints) {
14+
int size = endpoints.size();
15+
return endpoints.get(new Random().nextInt(size));
16+
}
17+
18+
public static void main(String[] args) {
19+
URL url = null;
20+
try {
21+
url = new URL("http://localhost:8088/api/hello");
22+
URI uri = url.toURI();
23+
System.out.println(uri.toASCIIString());
24+
} catch (MalformedURLException e) {
25+
e.printStackTrace();
26+
} catch (URISyntaxException e) {
27+
e.printStackTrace();
28+
}
29+
30+
}
31+
}

0 commit comments

Comments
 (0)