8000 作业03 · JavaCourse00/JavaCourseCodes@1215265 · GitHub
[go: up one dir, main page]

Skip to content

Commit 1215265

Browse files
committed
作业03
1 parent 155f2b5 commit 1215265

File tree

10 files changed

+249
-23
lines changed

10 files changed

+249
-23
lines changed

02nio/nio02/pom.xml

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,7 @@
5656
<dependency>
5757
<groupId>org.projectlombok</groupId>
5858
<artifactId>lombok</artifactId>
59+
<version>1.14.8</version>
5960
</dependency>
6061

6162
<!--
@@ -71,6 +72,12 @@
7172
</dependency>
7273
-->
7374

75+
<dependency>
76+
<groupId>com.squareup.okhttp</groupId>
77+
<artifactId>okhttp</artifactId>
78+
<version>2.7.5</version>
79+
</dependency>
80+
7481
</dependencies>
7582

7683
<build>
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
package com.jianjoy.http;
2+
3+
import com.squareup.okhttp.OkHttpClient;
4+
import com.squareup.okhttp.Request;
5+
import com.squareup.okhttp.Response;
6+
7+
import java.io.IOException;
8+
import java.util.concurrent.TimeUnit;
9+
10+
/**
11+
* Author: zhoujian
12+
* Description:http工具
13+
* Date: 2021/5/16 22:34
14+
*/
15+
public final class HttpUtil {
16+
17+
18+
private static final OkHttpClient CLIENT = new OkHttpClient();
19+
20+
private HttpUtil() {
21+
22+
}
23+
24+
static {
25+
CLIENT.setConnectTimeout(30, TimeUnit.SECONDS);
26+
CLIENT.setReadTimeout(30, TimeUnit.SECONDS);
27+
}
28+
29+
30+
/**
31+
* 发送get请求获取返回内容
32+
*
33+
* @param url
34+
* @return
35+
* @throws IOException
36+
*/
37+
public static String sendGet(String url) throws IOException {
38+
Request request = new Request.Builder()
39+
.url(url)
40+
.build();
41+
Response response = CLIENT.newCall(request).execute();
42+
return response.body().string();
43+
}
44+
45+
public static void main(String[] args) throws Exception {
46+
SimpleHttpServer.main(args);
47+
System.out.println(sendGet("http://localhost:8801"));
48+
}
49+
50+
51+
}
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package com.jianjoy.http;
2+
3+
import com.sun.net.httpserver.HttpExchange;
4+
import com.sun.net.httpserver.HttpHandler;
5+
import com.sun.net.httpserver.HttpServer;
6+
7+
import java.io.IOException;
8+
import java.net.InetSocketAddress;
9+
import java.util.Date;
10+
11+
/**
12+
* Author: zhoujian
13+
* Description:简单http server
14+
* Date: 2021/5/16 22:48
15+
*/
16+
public class SimpleHttpServer {
17+
18+
19+
public static void main(String[] args) throws IOException {
20+
createHttpServer(8801).start();
21+
createHttpServer(8802).start();
22+
System.out.println("SimpleHttpServer started.");
23+
}
24+
25+
private static HttpServer createHttpServer(int port) throws IOException {
26+
HttpServer httpServer = HttpServer.create(new InetSocketAddress(port), 0);
27+
httpServer.createContext("/", new HttpHandler() {
28+
@Override
29+
public void handle(HttpExchange httpExchange) throws IOException {
30+
byte[] content = ("Hello").getBytes("utf-8");
31+
System.out.println("server port:"+port+",handle request."+new Date());
32+
httpExchange.getResponseHeaders().add("Content-Type", "application/json; charset=UTF-8");
33+
httpExchange.sendResponseHeaders(200, content.length);
34+
httpExchange.getResponseBody().write(content);
35+
httpExchange.close();
36+
}
37+
});
38+
return httpServer;
39+
}
40+
41+
}

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

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

33

4+
import com.jianjoy.http.SimpleHttpServer;
45
import io.github.kimmking.gateway.inbound.HttpInboundServer;
56

67
import java.util.Arrays;
78

89
public class NettyServerApplication {
9-
10+
1011
public final static String GATEWAY_NAME = "NIOGateway";
1112
public final static String GATEWAY_VERSION = "3.0.0";
12-
13-
public static void main(String[] args) {
1413

15-
String proxyPort = System.getProperty("proxyPort","8888");
14+
public static void main(String[] args) throws Exception {
15+
//初始化后台服务
16+
SimpleHttpServer.main(args);
17+
18+
String proxyPort = System.getProperty("proxyPort", "8888");
1619

1720
// 这是之前的单个后端url的例子
1821
// String proxyServer = System.getProperty("proxyServer","http://localhost:8088");
@@ -22,14 +25,16 @@ public static void main(String[] args) {
2225

2326

2427
// 这是多个后端url走随机路由的例子
25-
String proxyServers = System.getProperty("proxyServers","http://localhost:8801,http://localhost:8802");
28+
String proxyServers = System.getProperty("proxyServers", "http://localhost:8801,http://localhost:8802");
2629
int port = Integer.parseInt(proxyPort);
27-
System.out.println(GATEWAY_NAME + " " + GATEWAY_VERSION +" starting...");
30+
System.out.println(GATEWAY_NAME + " " + GATEWAY_VERSION + " starting...");
2831
HttpInboundServer server = new HttpInboundServer(port, Arrays.asList(proxyServers.split(",")));
29-
System.out.println(GATEWAY_NAME + " " + GATEWAY_VERSION +" started at http://localhost:" + port + " for server:" + server.toString());
32+
System.out.println(GATEWAY_NAME + " " + GATEWAY_VERSION + " started at http://localhost:" + port + " for server:" + server.toString());
33+
34+
System.out.println("请访问接口地址:http://localhost:"+port+"/h1");
3035
try {
3136
server.run();
32-
}catch (Exception ex){
37+
} catch (Exception ex) {
3338
ex.printStackTrace();
3439
}
3540
}
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
package io.github.kimmking.gateway.filter;
2+
3+
import io.netty.channel.ChannelHandlerContext;
4+
import io.netty.handler.codec.http.FullHttpRequest;
5+
6+
/**
7+
* Author: zhoujian
8+
* Description:
9+
* Date: 2021/5/23 22:59
10+
*/
11+
public class MyHttpRequestFilter implements HttpRequestFilter {
12+
@Override
13+
public void filter(FullHttpRequest fullRequest, ChannelHandlerContext ctx) {
14+
fullRequest.headers().set("x-start", System.currentTimeMillis());
15+
}
16+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package io.github.kimmking.gateway.filter;
2+
3+
import io.netty.handler.codec.http.FullHttpResponse;
4+
5+
import java.util.UUID;
6+
7+
/**
8+
* Author: zhoujian
9+
* Description:
10+
* Date: 2021/5/23 23:00
11+
*/
12+
public class MyHttpResponseFilter implements HttpResponseFilter {
13+
14+
15+
@Override
16+
public void filter(FullHttpResponse response) {
17+
response.headers().set("x-server-time", System.currentTimeMillis());
18+
response.headers().set("x-id", UUID.randomUUID().toString());
19+
}
20+
}

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

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

3-
import io.github.kimmking.gateway.filter.HeaderHttpRequestFilter;
43
import io.github.kimmking.gateway.filter.HttpRequestFilter;
5-
import io.github.kimmking.gateway.outbound.httpclient4.HttpOutboundHandler;
4+
import io.github.kimmking.gateway.filter.MyHttpRequestFilter;
5+
import io.github.kimmking.gateway.outbound.okhttp.OkHttpOutboundHandler;
66
import io.netty.channel.ChannelHandlerContext;
77
import io.netty.channel.ChannelInboundHandlerAdapter;
88
import io.netty.handler.codec.http.FullHttpRequest;
@@ -16,14 +16,15 @@ public class HttpInboundHandler extends ChannelInboundHandlerAdapter {
1616

1717
private static Logger logger = LoggerFactory.getLogger(HttpInboundHandler.class);
1818
private final List<String> proxyServer;
19-
private HttpOutboundHandler handler;
20-
private HttpRequestFilter filter = new HeaderHttpRequestFilter();
21-
19+
private OkHttpOutboundHandler handler;
20+
private HttpRequestFilter filter = new MyHttpRequestFilter();
21+
22+
2223
public HttpInboundHandler(List<String> proxyServer) {
2324
this.proxyServer = proxyServer;
24-
this.handler = new HttpOutboundHandler(this.proxyServer);
25+
this.handler = new OkHttpOutboundHandler(proxyServer);
2526
}
26-
27+
2728
@Override
2829
public void channelReadComplete(ChannelHandlerContext ctx) {
2930
ctx.flush();
@@ -34,21 +35,33 @@ public void channelRead(ChannelHandlerContext ctx, Object msg) {
3435
try {
3536
//logger.info("channelRead流量接口请求开始,时间为{}", startTime);
3637
FullHttpRequest fullRequest = (FullHttpRequest) msg;
38+
String uri = fullRequest.uri();
39+
if (uri.contains("/h1")) {
40+
handleRequest(fullRequest, ctx);
41+
}
42+
3743
// String uri = fullRequest.uri();
3844
// //logger.info("接收到的请求url为{}", uri);
3945
// if (uri.contains("/test")) {
4046
// handlerTest(fullRequest, ctx);
4147
// }
42-
43-
handler.handle(fullRequest, ctx, filter);
44-
45-
} catch(Exception e) {
48+
49+
// handler.handle(fullRequest, ctx, filter);
50+
51+
} catch (Exception e) {
4652
e.printStackTrace();
4753
} finally {
4854
ReferenceCountUtil.release(msg);
4955
}
5056
}
5157

58+
private void handleRequest(FullHttpRequest fullRequest, ChannelHandlerContext ctx) {
59+
filter.filter(fullRequest, ctx);
60+
System.out.println("request header:"+fullRequest.headers());
61+
handler.handle(fullRequest, ctx);
62+
}
63+
64+
5265
// private void handlerTest(FullHttpRequest fullRequest, ChannelHandlerContext ctx) {
5366
// FullHttpResponse response = null;
5467
// try {
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
package io.github.kimmking.gateway.outbound.okhttp;
2+
3+
import com.jianjoy.http.HttpUtil;
4+
import io.github.kimmking.gateway.filter.MyHttpResponseFilter;
5+
import io.github.kimmking.gateway.router.MyEndpointRouter;
6+
import io.netty.buffer.Unpooled;
7+
import io.netty.channel.ChannelFutureListener;
8+
import io.netty.channel.ChannelHandlerContext;
9+
import io.netty.handler.codec.http.*;
10+
import org.slf4j.Logger;
11+
import org.slf4j.LoggerFactory;
12+
13+
import java.util.List;
14+
15+
import static io.netty.handler.codec.http.HttpHeaderNames.CONNECTION;
16+
import static io.netty.handler.codec.http.HttpHeaderValues.KEEP_ALIVE;
17+
18+
public cla 7D52 ss OkHttpOutboundHandler {
19+
private static Logger logger = LoggerFactory.getLogger(OkHttpOutboundHandler.class);
20+
private List<String> endpoints;
21+
22+
public OkHttpOutboundHandler(List<String> servers) {
23+
this.endpoints = servers;
24+
}
25+
26+
private MyEndpointRouter myEndpointRouter = new MyEndpointRouter();
27+
private MyHttpResponseFilter responseFilter = new MyHttpResponseFilter();
28+
29+
public void handle(FullHttpRequest fullRequest, ChannelHandlerContext ctx) {
30+
String serverUrl = myEndpointRouter.route(endpoints);
31+
System.out.println("random server url:" + serverUrl);
32+
FullHttpResponse response = null;
33+
try {
34+
String htmlContent = HttpUtil.sendGet(serverUrl);
35+
response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK
36+
, Unpooled.wrappedBuffer(htmlContent.getBytes("UTF-8")));
37+
responseFilter.filter(response);
38+
response.headers().set("Content-Type", "application/json");
39+
response.headers().setInt("Content-Length", response.content().readableBytes());
40+
System.out.println("response header:"+response.headers());
41+
} catch (Exception e) {
42+
logger.error("调用后台接口出错", e);
43+
response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NO_CONTENT);
44+
} finally {
45+
if (fullRequest != null) {
46+
if (!io.netty.handler.codec.http.HttpUtil.isKeepAlive(fullRequest)) {
47+
ctx.write(response).addListener(ChannelFutureListener.CLOSE);
48+
} else {
49+
response.headers().set(CONNECTION, KEEP_ALIVE);
50+
ctx.write(response);
51+
}
52+
}
53+
}
54+
55+
}
56+
}

02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/okhttp/OkhttpOutboundHandler.java

Lines changed: 0 additions & 4 deletions
This file was deleted.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
package io.github.kimmking.gateway.router;
2+
3+
import java.security.SecureRandom;
4+
import java.util.List;
5+
6+
/**
7+
* Author: zhoujian
8+
* Description: 随机路由
9+
* Date: 2021/5/23 23:03
10+
*/
11+
public class MyEndpointRouter implements HttpEndpointRouter {
12+
private static final SecureRandom RANDOM = new SecureRandom();
13+
14+
@Override
15+
public String route(List<String> endpoints) {
16+
int randomIndex = RANDOM.nextInt(endpoints.size());
17+
return endpoints.get(randomIndex);
18+
}
19+
20+
21+
}

0 commit comments

Comments
 (0)
0