From 30e6ff6ad6f8eb78f7fa6c59ee12caa72b3ccf39 Mon Sep 17 00:00:00 2001
From: baifukuan <1152465358@qq.com>
Date: Tue, 3 Nov 2020 23:53:14 +0800
Subject: [PATCH 1/7] =?UTF-8?q?=E6=9C=AC=E6=AC=A1=E6=8F=90=E4=BA=A4?=
=?UTF-8?q?=E4=B8=BB=E8=A6=81=E4=B8=BA=201.=E5=B0=86=E8=87=AA=E5=B7=B1?=
=?UTF-8?q?=E5=86=99=E7=9A=84HttpClient=E4=BB=A5=E7=BB=84=E4=BB=B6?=
=?UTF-8?q?=E7=9A=84=E5=BD=A2=E5=BC=8F=E9=9B=86=E6=88=90=EF=BC=8C2.?=
=?UTF-8?q?=E8=87=AA=E5=AE=9Afilter=E8=BF=87=E6=BB=A4=E5=99=A8?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
02nio/nio02/pom.xml | 10 +-
.../github/kimmking/gateway/ThreadPool.java | 27 ++++
.../gateway/filter/HttpRequestFilter.java | 2 +-
.../gateway/inbound/HttpInboundHandler.java | 103 +++++++++------
.../gateway/inbound/HttpInboundServer.java | 12 +-
.../{netty4 => }/NettyHttpClient.java | 34 ++---
.../httpclient4/HttpOutboundHandler.java | 60 +++++----
.../MyHttpOutboundHandler.java | 120 ++++++++++++++++++
8 files changed, 272 insertions(+), 96 deletions(-)
create mode 100644 02nio/nio02/src/main/java/io/github/kimmking/gateway/ThreadPool.java
rename 02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/{netty4 => }/NettyHttpClient.java (67%)
create mode 100644 02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/myselfhttpclient/MyHttpOutboundHandler.java
diff --git a/02nio/nio02/pom.xml b/02nio/nio02/pom.xml
index 6cbbeffd..fbbe5dd8 100644
--- a/02nio/nio02/pom.xml
+++ b/02nio/nio02/pom.xml
@@ -52,8 +52,13 @@
httpasyncclient
4.1.4
-
-
+
+ org.apache.httpcomponents
+ httpclient
+ 4.5.13
+
+
org.springframework.boot
spring-boot-starter-web
@@ -64,7 +69,6 @@
spring-boot-starter-test
test
- -->
diff --git a/02nio/nio02/src/main/java/io/github/kimmking/gateway/ThreadPool.java b/02nio/nio02/src/main/java/io/github/kimmking/gateway/ThreadPool.java
new file mode 100644
index 00000000..6f1f8765
--- /dev/null
+++ b/02nio/nio02/src/main/java/io/github/kimmking/gateway/ThreadPool.java
@@ -0,0 +1,27 @@
+package io.github.kimmking.gateway;
+
+import io.github.kimmking.gateway.outbound.httpclient4.NamedThreadFactory;
+
+import java.util.concurrent.ArrayBlockingQueue;
+import java.util.concurrent.RejectedExecutionHandler;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
+
+public class ThreadPool {
+
+ public static ThreadPoolExecutor getThreadPoolExecutor(){
+ int cores = Runtime.getRuntime().availableProcessors() * 2;
+ System.out.println(Runtime.getRuntime().availableProcessors());
+ long keepAliveTime = 1000;
+ int queueSize = 2048;
+ RejectedExecutionHandler handler = new ThreadPoolExecutor.CallerRunsPolicy();//.DiscardPolicy();
+ ThreadPoolExecutor proxyService = new ThreadPoolExecutor(cores,
+ cores,
+ keepAliveTime,
+ TimeUnit.MILLISECONDS,
+ new ArrayBlockingQueue<>(queueSize),
+ new NamedThreadFactory("proxyService"),
+ handler);
+ return proxyService;
+ }
+}
diff --git a/02nio/nio02/src/main/java/io/github/kimmking/gateway/filter/HttpRequestFilter.java b/02nio/nio02/src/main/java/io/github/kimmking/gateway/filter/HttpRequestFilter.java
index 31253b40..93ce0bf2 100644
--- a/02nio/nio02/src/main/java/io/github/kimmking/gateway/filter/HttpRequestFilter.java
+++ b/02nio/nio02/src/main/java/io/github/kimmking/gateway/filter/HttpRequestFilter.java
@@ -6,5 +6,5 @@
public interface HttpRequestFilter {
void filter(FullHttpRequest fullRequest, ChannelHandlerContext ctx);
-
+
}
diff --git a/02nio/nio02/src/main/java/io/github/kimmking/gateway/inbound/HttpInboundHandler.java b/02nio/nio02/src/main/java/io/github/kimmking/gateway/inbound/HttpInboundHandler.java
index 22fb2525..3f596cb0 100644
--- a/02nio/nio02/src/main/java/io/github/kimmking/gateway/inbound/HttpInboundHandler.java
+++ b/02nio/nio02/src/main/java/io/github/kimmking/gateway/inbound/HttpInboundHandler.java
@@ -1,24 +1,38 @@
package io.github.kimmking.gateway.inbound;
+import io.github.kimmking.gateway.filter.HttpRequestFilter;
import io.github.kimmking.gateway.outbound.httpclient4.HttpOutboundHandler;
+import io.github.kimmking.gateway.outbound.myselfhttpclient.MyHttpOutboundHandler;
+import io.netty.buffer.Unpooled;
+import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
-import io.netty.handler.codec.http.FullHttpRequest;
+import io.netty.handler.codec.http.*;
import io.netty.util.ReferenceCountUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public class HttpInboundHandler extends ChannelInboundHandlerAdapter {
+import static io.netty.handler.codec.http.HttpHeaderValues.KEEP_ALIVE;
+import static io.netty.handler.codec.http.HttpResponseStatus.NO_CONTENT;
+import static io.netty.handler.codec.http.HttpResponseStatus.OK;
+import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;
+
+public class HttpInboundHandler extends ChannelInboundHandlerAdapter implements HttpRequestFilter {
private static Logger logger = LoggerFactory.getLogger(HttpInboundHandler.class);
private final String proxyServer;
private HttpOutboundHandler handler;
-
+ // 自己写的Httpclient组件
+ private MyHttpOutboundHandler myHandler;
+
public HttpInboundHandler(String proxyServer) {
this.proxyServer = proxyServer;
+ // 老师
handler = new HttpOutboundHandler(this.proxyServer);
+ // 自己写的Httpclient组件
+ myHandler = new MyHttpOutboundHandler(this.proxyServer);
}
-
+
@Override
public void channelReadComplete(ChannelHandlerContext ctx) {
ctx.flush();
@@ -27,50 +41,55 @@ public void channelReadComplete(ChannelHandlerContext ctx) {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
try {
- //logger.info("channelRead流量接口请求开始,时间为{}", startTime);
+ long startTime = System.currentTimeMillis();
+ logger.info("channelRead流量接口请求开始,时间为{}", startTime);
FullHttpRequest fullRequest = (FullHttpRequest) msg;
-// String uri = fullRequest.uri();
-// //logger.info("接收到的请求url为{}", uri);
-// if (uri.contains("/test")) {
-// handlerTest(fullRequest, ctx);
-// }
-
- handler.handle(fullRequest, ctx);
-
- } catch(Exception e) {
+ // 自定义过滤器
+ filter(fullRequest,ctx);
+ // 自己写的HttpClient
+ myHandler.handler(fullRequest,ctx);
+ // 老师写的
+ // handler.handle(fullRequest, ctx);
+
+ } catch (Exception e) {
e.printStackTrace();
} finally {
ReferenceCountUtil.release(msg);
}
}
-// private void handlerTest(FullHttpRequest fullRequest, ChannelHandlerContext ctx) {
-// FullHttpResponse response = null;
-// try {
-// String value = "hello,kimmking";
-// response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(value.getBytes("UTF-8")));
-// response.headers().set("Content-Type", "application/json");
-// response.headers().setInt("Content-Length", response.content().readableBytes());
-//
-// } catch (Exception e) {
-// logger.error("处理测试接口出错", e);
-// response = new DefaultFullHttpResponse(HTTP_1_1, NO_CONTENT);
-// } finally {
-// if (fullRequest != null) {
-// if (!HttpUtil.isKeepAlive(fullRequest)) {
-// ctx.write(response).addListener(ChannelFutureListener.CLOSE);
-// } else {
-// response.headers().set(CONNECTION, KEEP_ALIVE);
-// ctx.write(response);
-// }
-// }
-// }
-// }
-//
-// @Override
-// public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
-// cause.printStackTrace();
-// ctx.close();
-// }
+ @Override
+ public void filter(FullHttpRequest fullRequest, ChannelHandlerContext ctx) {
+ HttpHeaders headers = fullRequest.headers();
+ headers.set("nio","BAIFUKUAN");
+ }
+ private void handlerTest(FullHttpRequest fullRequest, ChannelHandlerContext ctx) {
+ FullHttpResponse response = null;
+ try {
+ String value = "hello,kimmking";
+ response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(value.getBytes("UTF-8")));
+ response.headers().set("Content-Type", "application/json");
+ response.headers().setInt("Content-Length", response.content().readableBytes());
+
+ } catch (Exception e) {
+ logger.error("处理测试接口出错", e);
+ response = new DefaultFullHttpResponse(HTTP_1_1, NO_CONTENT);
+ } finally {
+ if (fullRequest != null) {
+ if (!HttpUtil.isKeepAlive(fullRequest)) {
+ ctx.write(response).addListener(ChannelFutureListener.CLOSE);
+ } else {
+ response.headers().set("CONNECTION", KEEP_ALIVE);
+ ctx.write(response);
+ }
+ }
+ }
+ }
+
+ @Override
+ public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
+ cause.printStackTrace();
+ ctx.close();
+ }
}
diff --git a/02nio/nio02/src/main/java/io/github/kimmking/gateway/inbound/HttpInboundServer.java b/02nio/nio02/src/main/java/io/github/kimmking/gateway/inbound/HttpInboundServer.java
index 071fa9bc..28d1558b 100644
--- a/02nio/nio02/src/main/java/io/github/kimmking/gateway/inbound/HttpInboundServer.java
+++ b/02nio/nio02/src/main/java/io/github/kimmking/gateway/inbound/HttpInboundServer.java
@@ -18,18 +18,18 @@ public class HttpInboundServer {
private static Logger logger = LoggerFactory.getLogger(HttpInboundServer.class);
private int port;
-
+
private String proxyServer;
public HttpInboundServer(int port, String proxyServer) {
- this.port=port;
+ this.port = port;
this.proxyServer = proxyServer;
}
public void run() throws Exception {
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
- EventLoopGroup workerGroup = new NioEventLoopGroup(16);
+ EventLoopGroup workerGroup = new NioEventLoopGroup(8);
try {
ServerBootstrap b = new ServerBootstrap();
@@ -43,8 +43,10 @@ public void run() throws Exception {
.childOption(ChannelOption.SO_KEEPALIVE, true)
.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
- b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
- .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new HttpInboundInitializer(this.proxyServer));
+ b.group(bossGroup, workerGroup)
+ .channel(NioServerSocketChannel.class)
+ .handler(new LoggingHandler(LogLevel.INFO))
+ .childHandler(new HttpInboundInitializer(this.proxyServer));
Channel ch = b.bind(port).sync().channel();
logger.info("开启netty http服务器,监听地址和端口为 http://127.0.0.1:" + port + '/');
diff --git a/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/netty4/NettyHttpClient.java b/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/NettyHttpClient.java
similarity index 67%
rename from 02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/netty4/NettyHttpClient.java
rename to 02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/NettyHttpClient.java
index 79aeb148..2b043ddb 100644
--- a/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/netty4/NettyHttpClient.java
+++ b/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/NettyHttpClient.java
@@ -1,17 +1,17 @@
-//package io.github.kimmking.gateway.outbound;
-//
-//import io.netty.bootstrap.Bootstrap;
-//import io.netty.channel.ChannelFuture;
-//import io.netty.channel.ChannelInitializer;
-//import io.netty.channel.ChannelOption;
-//import io.netty.channel.EventLoopGroup;
-//import io.netty.channel.nio.NioEventLoopGroup;
-//import io.netty.channel.socket.SocketChannel;
-//import io.netty.channel.socket.nio.NioSocketChannel;
-//import io.netty.handler.codec.http.HttpRequestEncoder;
-//import io.netty.handler.codec.http.HttpResponseDecoder;
-//
-//public class NettyHttpClient {
+// package io.github.kimmking.gateway.outbound;
+//
+// import io.netty.bootstrap.Bootstrap;
+// import io.netty.channel.ChannelFuture;
+// import io.netty.channel.ChannelInitializer;
+// import io.netty.channel.ChannelOption;
+// import io.netty.channel.EventLoopGroup;
+// import io.netty.channel.nio.NioEventLoopGroup;
+// import io.netty.channel.socket.SocketChannel;
+// import io.netty.channel.socket.nio.NioSocketChannel;
+// import io.netty.handler.codec.http.HttpRequestEncoder;
+// import io.netty.handler.codec.http.HttpResponseDecoder;
+//
+// public class NettyHttpClient {
// public void connect(String host, int port) throws Exception {
// EventLoopGroup workerGroup = new NioEventLoopGroup();
//
@@ -25,7 +25,7 @@
// public void initChannel(SocketChannel ch) throws Exception {
// // 客户端接收到的是httpResponse响应,所以要使用HttpResponseDecoder进行解码
// ch.pipeline().addLast(new HttpResponseDecoder());
-// 客户端发送的是httprequest,所以要使用HttpRequestEncoder进行编码
+// // 客户端发送的是httprequest,所以要使用HttpRequestEncoder进行编码
// ch.pipeline().addLast(new HttpRequestEncoder());
// ch.pipeline().addLast(new HttpClientOutboundHandler());
// }
@@ -34,7 +34,7 @@
// // Start the client.
// ChannelFuture f = b.connect(host, port).sync();
//
-//
+//
// f.channel().write(request);
// f.channel().flush();
// f.channel().closeFuture().sync();
@@ -48,4 +48,4 @@
// NettyHttpClient client = new NettyHttpClient();
// client.connect("127.0.0.1", 8844);
// }
-//}
\ No newline at end of file
+// }
\ No newline at end of file
diff --git a/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/httpclient4/HttpOutboundHandler.java b/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/httpclient4/HttpOutboundHandler.java
index 856dc168..0f8c57a8 100644
--- a/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/httpclient4/HttpOutboundHandler.java
+++ b/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/httpclient4/HttpOutboundHandler.java
@@ -24,41 +24,45 @@
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;
public class HttpOutboundHandler {
-
+
private CloseableHttpAsyncClient httpclient;
private ExecutorService proxyService;
private String backendUrl;
-
- public HttpOutboundHandler(String backendUrl){
- this.backendUrl = backendUrl.endsWith("/")?backendUrl.substring(0,backendUrl.length()-1):backendUrl;
- int cores = Runtime.getRuntime().availableProcessors() * 2;
+
+ public HttpOutboundHandler(String backendUrl) {
+ this.backendUrl = backendUrl.endsWith("/") ? backendUrl.substring(0, backendUrl.length() - 1) : backendUrl;
+ int cores = Runtime.getRuntime().availableProcessors() * 1;
long keepAliveTime = 1000;
int queueSize = 2048;
RejectedExecutionHandler handler = new ThreadPoolExecutor.CallerRunsPolicy();//.DiscardPolicy();
- proxyService = new ThreadPoolExecutor(cores, cores,
- keepAliveTime, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(queueSize),
- new NamedThreadFactory("proxyService"), handler);
-
+ proxyService = new ThreadPoolExecutor(cores,
+ cores,
+ keepAliveTime,
+ TimeUnit.MILLISECONDS,
+ new ArrayBlockingQueue<>(queueSize),
+ new NamedThreadFactory("proxyService"),
+ handler);
+
IOReactorConfig ioConfig = IOReactorConfig.custom()
.setConnectTimeout(1000)
.setSoTimeout(1000)
.setIoThreadCount(cores)
.setRcvBufSize(32 * 1024)
.build();
-
+
httpclient = HttpAsyncClients.custom().setMaxConnTotal(40)
.setMaxConnPerRoute(8)
.setDefaultIOReactorConfig(ioConfig)
- .setKeepAliveStrategy((response,context) -> 6000)
+ .setKeepAliveStrategy((response, context) -> 6000)
.build();
httpclient.start();
}
-
+
public void handle(final FullHttpRequest fullRequest, final ChannelHandlerContext ctx) {
final String url = this.backendUrl + fullRequest.uri();
- proxyService.submit(()->fetchGet(fullRequest, ctx, url));
+ proxyService.submit(() -> fetchGet(fullRequest, ctx, url));
}
-
+
private void fetchGet(final FullHttpRequest inbound, final ChannelHandlerContext ctx, final String url) {
final HttpGet httpGet = new HttpGet(url);
//httpGet.setHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE);
@@ -71,23 +75,23 @@ public void completed(final HttpResponse endpointResponse) {
} catch (Exception e) {
e.printStackTrace();
} finally {
-
+
}
}
-
+
@Override
public void failed(final Exception ex) {
httpGet.abort();
ex.printStackTrace();
}
-
+
@Override
public void cancelled() {
httpGet.abort();
}
});
}
-
+
private void handleResponse(final FullHttpRequest fullRequest, final ChannelHandlerContext ctx, final HttpResponse endpointResponse) throws Exception {
FullHttpResponse response = null;
try {
@@ -95,21 +99,21 @@ private void handleResponse(final FullHttpRequest fullRequest, final ChannelHand
// response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(value.getBytes("UTF-8")));
// response.headers().set("Content-Type", "application/json");
// response.headers().setInt("Content-Length", response.content().readableBytes());
-
-
+
+
byte[] body = EntityUtils.toByteArray(endpointResponse.getEntity());
// System.out.println(new String(body));
// System.out.println(body.length);
-
+
response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(body));
response.headers().set("Content-Type", "application/json");
response.headers().setInt("Content-Length", Integer.parseInt(endpointResponse.getFirstHeader("Content-Length").getValue()));
-
+
// for (Header e : endpointResponse.getAllHeaders()) {
// //response.headers().set(e.getName(),e.getValue());
// System.out.println(e.getName() + " => " + e.getValue());
// }
-
+
} catch (Exception e) {
e.printStackTrace();
response = new DefaultFullHttpResponse(HTTP_1_1, NO_CONTENT);
@@ -119,20 +123,20 @@ private void handleResponse(final FullHttpRequest fullRequest, final ChannelHand
if (!HttpUtil.isKeepAlive(fullRequest)) {
ctx.write(response).addListener(ChannelFutureListener.CLOSE);
} else {
- //response.headers().set(CONNECTION, KEEP_ALIVE);
+ // response.headers().set(CONNECTION, KEEP_ALIVE);
ctx.write(response);
}
}
ctx.flush();
//ctx.close();
}
-
+
}
-
+
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
ctx.close();
}
-
-
+
+
}
diff --git a/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/myselfhttpclient/MyHttpOutboundHandler.java b/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/myselfhttpclient/MyHttpOutboundHandler.java
new file mode 100644
index 00000000..1d6b6d1f
--- /dev/null
+++ b/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/myselfhttpclient/MyHttpOutboundHandler.java
@@ -0,0 +1,120 @@
+package io.github.kimmking.gateway.outbound.myselfhttpclient;
+
+import io.github.kimmking.gateway.ThreadPool;
+import io.netty.buffer.Unpooled;
+import io.netty.channel.ChannelFutureListener;
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.handler.codec.http.*;
+import org.apache.http.Header;
+import org.apache.http.HttpResponse;
+import org.apache.http.client.ResponseHandler;
+import org.apache.http.client.config.RequestConfig;
+import org.apache.http.client.methods.HttpGet;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClients;
+import org.apache.http.util.EntityUtils;
+import org.springframework.util.StringUtils;
+
+import java.io.IOException;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ThreadPoolExecutor;
+
+import static io.netty.handler.codec.http.HttpResponseStatus.NO_CONTENT;
+import static io.netty.handler.codec.http.HttpResponseStatus.OK;
+import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;
+
+public class MyHttpOutboundHandler {
+
+ private static CloseableHttpClient client;
+ private String backendUrl;
+ private ThreadPoolExecutor proxyService;
+ public MyHttpOutboundHandler(String backendUrl) {
+ this.backendUrl = backendUrl.endsWith("/") ? backendUrl.substring(0, backendUrl.length() - 1) : backendUrl;
+ client = HttpClients.createDefault();
+ proxyService = ThreadPool.getThreadPoolExecutor();
+ }
+
+ public void handler(FullHttpRequest fullRequest, ChannelHandlerContext ctx) {
+ final String url = this.backendUrl + fullRequest.uri();
+ if (StringUtils.isEmpty(url)) {
+ return;
+ }
+ // 创建httpGet请求对象
+ final HttpGet httpGet = new HttpGet(url);
+ // 设置时间等参数
+ RequestConfig config = RequestConfig.custom()
+ .setConnectTimeout(1000) // 链接超时时间
+ .setConnectionRequestTimeout(1000) // 连接请求超时时间
+ .setSocketTimeout(1000) // 套接字超时时间
+ .build();
+ // HttpHeaders httpHeaders = fullRequest.headers();
+ // List> headerList = httpHeaders.entries();
+ // 设置全部请求头到对后端调用的请求头中
+ // headerList.forEach(header -> {
+ // Map.Entry map = header;
+ // httpGet.addHeader(map.getKey(), map.getValue());
+ // });
+ httpGet.setConfig(config);
+ proxyService.submit(() -> doGet(httpGet, fullRequest, ctx));
+ }
+
+ private void doGet(HttpGet httpGet,FullHttpRequest fullRequest,ChannelHandlerContext ctx){
+ try {
+ // 执行请求
+ client.execute(httpGet, new ResponseHandler() {
+ @Override
+ public HttpResponse handleResponse(HttpResponse httpResponse) {
+ try {
+ // 返回数据到浏览器
+ doHandleResponse(fullRequest, ctx, httpResponse);
+ } catch (Exception e) {
+ e.printStackTrace();
+ } finally {
+ }
+ return httpResponse;
+ }
+ });
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+
+ /**
+ * 将服务端返回的获取的值,返回到浏览器端
+ *
+ * @param fullRequest
+ * @param ctx
+ * @param endpointResponse
+ * @throws Exception
+ */
+ public void doHandleResponse(final FullHttpRequest fullRequest, final ChannelHandlerContext ctx, final HttpResponse endpointResponse) throws Exception {
+ FullHttpResponse response = null;
+ try {
+ byte[] body = EntityUtils.toByteArray(endpointResponse.getEntity());
+ response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(body));
+ response.headers().set("Content-Type", "application/json");
+ response.headers().setInt("Content-Length", Integer.parseInt(endpointResponse.getFirstHeader("Content-Length").getValue()));
+ } catch (Exception e) {
+ e.printStackTrace();
+ response = new DefaultFullHttpResponse(HTTP_1_1, NO_CONTENT);
+ exceptionCaught(ctx, e);
+ } finally {
+ if (fullRequest != null) {
+ if (!HttpUtil.isKeepAlive(fullRequest)) {
+ ctx.write(response).addListener(ChannelFutureListener.CLOSE);
+ } else {
+ // response.headers().set(CONNECTION, KEEP_ALIVE);
+ ctx.write(response);
+ }
+ }
+ ctx.flush();
+ ctx.close();
+ }
+ }
+
+ public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
+ cause.printStackTrace();
+ ctx.close();
+ }
+}
From b01830651a261bbc50da3527df7f12182b689adc Mon Sep 17 00:00:00 2001
From: baifukuan <1152465358@qq.com>
Date: Sun, 8 Nov 2020 12:49:26 +0800
Subject: [PATCH 2/7] =?UTF-8?q?=E6=8F=90=E4=BA=A4=E8=87=AA=E5=AE=9A?=
=?UTF-8?q?=E4=B9=89OutboundHandler?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
.../myselfhttpclient/MyHttpOutboundHandler.java | 14 +++++++-------
1 file changed, 7 insertions(+), 7 deletions(-)
diff --git a/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/myselfhttpclient/MyHttpOutboundHandler.java b/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/myselfhttpclient/MyHttpOutboundHandler.java
index 1d6b6d1f..3c08c7c6 100644
--- a/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/myselfhttpclient/MyHttpOutboundHandler.java
+++ b/02nio/nio02/src/main/java/io/github/kimmking/gateway/outbound/myselfhttpclient/MyHttpOutboundHandler.java
@@ -13,6 +13,7 @@
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
+import org.hibernate.validator.internal.util.stereotypes.ThreadSafe;
import org.springframework.util.StringUtils;
import java.io.IOException;
@@ -34,7 +35,6 @@ public MyHttpOutboundHandler(String backendUrl) {
client = HttpClients.createDefault();
proxyService = ThreadPool.getThreadPoolExecutor();
}
-
public void handler(FullHttpRequest fullRequest, ChannelHandlerContext ctx) {
final String url = this.backendUrl + fullRequest.uri();
if (StringUtils.isEmpty(url)) {
@@ -48,13 +48,13 @@ public void handler(FullHttpRequest fullRequest, ChannelHandlerContext ctx) {
.setConnectionRequestTimeout(1000) // 连接请求超时时间
.setSocketTimeout(1000) // 套接字超时时间
.build();
- // HttpHeaders httpHeaders = fullRequest.headers();
- // List> headerList = httpHeaders.entries();
+ HttpHeaders httpHeaders = fullRequest.headers();
+ List> headerList = httpHeaders.entries();
// 设置全部请求头到对后端调用的请求头中
- // headerList.forEach(header -> {
- // Map.Entry map = header;
- // httpGet.addHeader(map.getKey(), map.getValue());
- // });
+ headerList.forEach(header -> {
+ Map.Entry map = header;
+ httpGet.addHeader(map.getKey(), map.getValue());
+ });
httpGet.setConfig(config);
proxyService.submit(() -> doGet(httpGet, fullRequest, ctx));
}
From 331483d2f50f872af298bd6b954b01ec0c6e364a Mon Sep 17 00:00:00 2001
From: baifukuan <1152465358@qq.com>
Date: Wed, 16 Dec 2020 23:53:01 +0800
Subject: [PATCH 3/7] =?UTF-8?q?httpClient=20Netty=20Client=20=E6=9C=AA?=
=?UTF-8?q?=E5=AE=9E=E7=8E=B0?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
07rpc/rpc01/rpcfx-core/pom.xml | 7 ++-
.../io/kimmking/rpcfx/api/RpcfxRequest.java | 10 ++++
.../io/kimmking/rpcfx/api/RpcfxResolver.java | 4 +-
.../kimmking/rpcfx/client/RpcProxyCache.java | 40 +++++++++++++++
.../kimmking/rpcfx/client/RpcfxByteBuddy.java | 40 +++++++++++++++
.../io/kimmking/rpcfx/client/RpcfxProxy.java | 6 +++
.../io/kimmking/rpcfx/proxy/ByteBuddy.java | 4 ++
.../RpcfxInvocationHandler.java} | 49 ++++++++-----------
.../kimmking/rpcfx/server/RpcfxInvoker.java | 31 ++++++++----
.../io/kimmking/rpcfx/demo/api/Order.java | 2 +
.../demo/consumer/RpcfxClientApplication.java | 15 +++---
.../rpcfx/demo/provider/DemoResolver.java | 9 ++--
.../demo/provider/RpcfxServerApplication.java | 4 +-
.../rpcfx/demo/provider/UserServiceImpl.java | 1 +
14 files changed, 170 insertions(+), 52 deletions(-)
create mode 100644 07rpc/rpc01/rpcfx-core/src/main/java/io/kimmking/rpcfx/client/RpcProxyCache.java
create mode 100644 07rpc/rpc01/rpcfx-core/src/main/java/io/kimmking/rpcfx/client/RpcfxByteBuddy.java
create mode 100644 07rpc/rpc01/rpcfx-core/src/main/java/io/kimmking/rpcfx/client/RpcfxProxy.java
create mode 100644 07rpc/rpc01/rpcfx-core/src/main/java/io/kimmking/rpcfx/proxy/ByteBuddy.java
rename 07rpc/rpc01/rpcfx-core/src/main/java/io/kimmking/rpcfx/{client/Rpcfx.java => proxy/RpcfxInvocationHandler.java} (62%)
diff --git a/07rpc/rpc01/rpcfx-core/pom.xml b/07rpc/rpc01/rpcfx-core/pom.xml
index 8f11dc5d..d258f4bf 100644
--- a/07rpc/rpc01/rpcfx-core/pom.xml
+++ b/07rpc/rpc01/rpcfx-core/pom.xml
@@ -51,6 +51,11 @@
-
+
+ net.bytebuddy
+ byte-buddy
+ 1.7.11
+
+
diff --git a/07rpc/rpc01/rpcfx-core/src/main/java/io/kimmking/rpcfx/api/RpcfxRequest.java b/07rpc/rpc01/rpcfx-core/src/main/java/io/kimmking/rpcfx/api/RpcfxRequest.java
index 3a4de089..749a44eb 100644
--- a/07rpc/rpc01/rpcfx-core/src/main/java/io/kimmking/rpcfx/api/RpcfxRequest.java
+++ b/07rpc/rpc01/rpcfx-core/src/main/java/io/kimmking/rpcfx/api/RpcfxRequest.java
@@ -8,6 +8,8 @@ public class RpcfxRequest {
private Object[] params;
+ private Class>[] parameterTypes;
+
public String getServiceClass() {
return serviceClass;
}
@@ -31,4 +33,12 @@ public Object[] getParams() {
public void setParams(Object[] params) {
this.params = params;
}
+
+ public Class>[] getParameterTypes() {
+ return parameterTypes;
+ }
+
+ public void setParameterTypes(Class>[] parameterTypes) {
+ this.parameterTypes = parameterTypes;
+ }
}
diff --git a/07rpc/rpc01/rpcfx-core/src/main/java/io/kimmking/rpcfx/api/RpcfxResolver.java b/07rpc/rpc01/rpcfx-core/src/main/java/io/kimmking/rpcfx/api/RpcfxResolver.java
index f7c48068..3b216069 100644
--- a/07rpc/rpc01/rpcfx-core/src/main/java/io/kimmking/rpcfx/api/RpcfxResolver.java
+++ b/07rpc/rpc01/rpcfx-core/src/main/java/io/kimmking/rpcfx/api/RpcfxResolver.java
@@ -1,7 +1,7 @@
package io.kimmking.rpcfx.api;
-public interface RpcfxResolver {
+public interface RpcfxResolver {
- Object resolve(String serviceClass);
+ T resolve(Class t);
}
diff --git a/07rpc/rpc01/rpcfx-core/src/main/java/io/kimmking/rpcfx/client/RpcProxyCache.java b/07rpc/rpc01/rpcfx-core/src/main/java/io/kimmking/rpcfx/client/RpcProxyCache.java
new file mode 100644
index 00000000..0050cd7f
--- /dev/null
+++ b/07rpc/rpc01/rpcfx-core/src/main/java/io/kimmking/rpcfx/client/RpcProxyCache.java
@@ -0,0 +1,40 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package io.kimmking.rpcfx.client;
+
+import java.util.concurrent.ConcurrentHashMap;
+
+/**
+ * @author lw1243925457
+ */
+public class RpcProxyCache {
+
+ private static ConcurrentHashMap proxyCache = new ConcurrentHashMap<>();
+
+ Object getProxy(String className) {
+ return proxyCache.get(className);
+ }
+
+ Boolean isExit(String className) {
+ return proxyCache.containsKey(className);
+ }
+
+ void add(String className, Object proxy) {
+ proxyCache.put(className, proxy);
+ }
+}
diff --git a/07rpc/rpc01/rpcfx-core/src/main/java/io/kimmking/rpcfx/client/RpcfxByteBuddy.java b/07rpc/rpc01/rpcfx-core/src/main/java/io/kimmking/rpcfx/client/RpcfxByteBuddy.java
new file mode 100644
index 00000000..b7bac635
--- /dev/null
+++ b/07rpc/rpc01/rpcfx-core/src/main/java/io/kimmking/rpcfx/client/RpcfxByteBuddy.java
@@ -0,0 +1,40 @@
+package io.kimmking.rpcfx.client;
+
+import com.alibaba.fastjson.parser.ParserConfig;
+import io.kimmking.rpcfx.proxy.RpcfxInvocationHandler;
+import net.bytebuddy.ByteBuddy;
+import net.bytebuddy.implementation.InvocationHandlerAdapter;
+import net.bytebuddy.matcher.ElementMatchers;
+
+public final class RpcfxByteBuddy extends RpcProxyCache implements RpcfxProxy{
+
+ @Override
+ public T create(final Class serviceClass, final String url) {
+ if (isExit(serviceClass.getName())) {
+ return (T) getProxy(serviceClass.getName());
+ }
+ T proxy = newProxy(serviceClass, url);
+ add(serviceClass.getName(), proxy);
+ return proxy;
+ }
+
+ public T newProxy(final Class serviceClass, final String url) {
+ // 使用 ByteBuddy
+ // 0. 替换动态代理 -> AOP
+ T byteBuddy = null;
+ try {
+ byteBuddy = new ByteBuddy()
+ .subclass(serviceClass)
+ .method(ElementMatchers.any())
+ .intercept(InvocationHandlerAdapter.of(new RpcfxInvocationHandler(serviceClass, url)))
+ .make()
+ .load(serviceClass.getClassLoader())
+ .getLoaded().newInstance();
+ } catch (InstantiationException e) {
+ e.printStackTrace();
+ } catch (IllegalAccessException e) {
+ e.printStackTrace();
+ }
+ return byteBuddy;
+ }
+}
diff --git a/07rpc/rpc01/rpcfx-core/src/main/java/io/kimmking/rpcfx/client/RpcfxProxy.java b/07rpc/rpc01/rpcfx-core/src/main/java/io/kimmking/rpcfx/client/RpcfxProxy.java
new file mode 100644
index 00000000..ab51733b
--- /dev/null
+++ b/07rpc/rpc01/rpcfx-core/src/main/java/io/kimmking/rpcfx/client/RpcfxProxy.java
@@ -0,0 +1,6 @@
+package io.kimmking.rpcfx.client;
+
+public interface RpcfxProxy {
+
+ T create(final Class serviceClass, final String url);
+}
diff --git a/07rpc/rpc01/rpcfx-core/src/main/java/io/kimmking/rpcfx/proxy/ByteBuddy.java b/07rpc/rpc01/rpcfx-core/src/main/java/io/kimmking/rpcfx/proxy/ByteBuddy.java
new file mode 100644
index 00000000..106b9c9b
--- /dev/null
+++ b/07rpc/rpc01/rpcfx-core/src/main/java/io/kimmking/rpcfx/proxy/ByteBuddy.java
@@ -0,0 +1,4 @@
+package io.kimmking.rpcfx.proxy;
+
+public class ByteBuddy {
+}
diff --git a/07rpc/rpc01/rpcfx-core/src/main/java/io/kimmking/rpcfx/client/Rpcfx.java b/07rpc/rpc01/rpcfx-core/src/main/java/io/kimmking/rpcfx/proxy/RpcfxInvocationHandler.java
similarity index 62%
rename from 07rpc/rpc01/rpcfx-core/src/main/java/io/kimmking/rpcfx/client/Rpcfx.java
rename to 07rpc/rpc01/rpcfx-core/src/main/java/io/kimmking/rpcfx/proxy/RpcfxInvocationHandler.java
index 3d7b3788..4d3d2500 100644
--- a/07rpc/rpc01/rpcfx-core/src/main/java/io/kimmking/rpcfx/client/Rpcfx.java
+++ b/07rpc/rpc01/rpcfx-core/src/main/java/io/kimmking/rpcfx/proxy/RpcfxInvocationHandler.java
@@ -1,5 +1,4 @@
-package io.kimmking.rpcfx.client;
-
+package io.kimmking.rpcfx.proxy;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.ParserConfig;
@@ -9,26 +8,13 @@
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
+import org.aopalliance.intercept.MethodInterceptor;
import java.io.IOException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
-import java.lang.reflect.Proxy;
-
-public final class Rpcfx {
-
- static {
- ParserConfig.getGlobalInstance().addAccept("io.kimmking");
- }
- public static T create(final Class serviceClass, final String url) {
-
- // 0. 替换动态代理 -> AOP
- return (T) Proxy.newProxyInstance(Rpcfx.class.getClassLoader(), new Class[]{serviceClass}, new RpcfxInvocationHandler(serviceClass, url));
-
- }
-
- public static class RpcfxInvocationHandler implements InvocationHandler {
+public class RpcfxInvocationHandler implements InvocationHandler {
public static final MediaType JSONTYPE = MediaType.get("application/json; charset=utf-8");
@@ -37,6 +23,7 @@ public static class RpcfxInvocationHandler implements InvocationHandler {
public RpcfxInvocationHandler(Class serviceClass, String url) {
this.serviceClass = serviceClass;
this.url = url;
+ ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
}
// 可以尝试,自己去写对象序列化,二进制还是文本的,,,rpcfx是xml自定义序列化、反序列化,json: code.google.com/p/rpcfx
@@ -45,20 +32,25 @@ public RpcfxInvocationHandler(Class serviceClass, String url) {
@Override
public Object invoke(Object proxy, Method method, Object[] params) throws Throwable {
- RpcfxRequest request = new RpcfxRequest();
- request.setServiceClass(this.serviceClass.getName());
- request.setMethod(method.getName());
- request.setParams(params);
+ return invokePost(method, params);
+ }
- RpcfxResponse response = post(request, url);
+ private Object invokePost(Method method, Object[] params) throws IOException {
+ RpcfxRequest request = new RpcfxRequest();
+ request.setServiceClass(this.serviceClass.getName());
+ request.setMethod(method.getName());
+ request.setParams(params);
+ request.setParameterTypes(method.getParameterTypes());
- // 这里判断response.status,处理异常
- // 考虑封装一个全局的RpcfxException
+ RpcfxResponse response = post(request, url);
- return JSON.parse(response.getResult().toString());
- }
+ // 这里判断response.status,处理异常
+ // 考虑封装一个全局的RpcfxException
- private RpcfxResponse post(RpcfxRequest req, String url) throws IOException {
+ return JSON.parse(response.getResult().toString());
+ }
+
+ private RpcfxResponse post(RpcfxRequest req, String url) throws IOException {
String reqJson = JSON.toJSONString(req);
System.out.println("req json: "+reqJson);
@@ -73,5 +65,4 @@ private RpcfxResponse post(RpcfxRequest req, String url) throws IOException {
System.out.println("resp json: "+respJson);
return JSON.parseObject(respJson, RpcfxResponse.class);
}
- }
-}
+ }
\ No newline at end of file
diff --git a/07rpc/rpc01/rpcfx-core/src/main/java/io/kimmking/rpcfx/server/RpcfxInvoker.java b/07rpc/rpc01/rpcfx-core/src/main/java/io/kimmking/rpcfx/server/RpcfxInvoker.java
index a6f77dac..1c62943a 100644
--- a/07rpc/rpc01/rpcfx-core/src/main/java/io/kimmking/rpcfx/server/RpcfxInvoker.java
+++ b/07rpc/rpc01/rpcfx-core/src/main/java/io/kimmking/rpcfx/server/RpcfxInvoker.java
@@ -14,25 +14,31 @@ public class RpcfxInvoker {
private RpcfxResolver resolver;
- public RpcfxInvoker(RpcfxResolver resolver){
+
+ public RpcfxInvoker(RpcfxResolver resolver) {
this.resolver = resolver;
}
- public RpcfxResponse invoke(RpcfxRequest request) {
+ public RpcfxResponse invoke(RpcfxRequest request){
RpcfxResponse response = new RpcfxResponse();
String serviceClass = request.getServiceClass();
-
- // 作业1:改成泛型和反射
- Object service = resolver.resolve(serviceClass);//this.applicationContext.getBean(serviceClass);
-
+ Object[] params = request.getParams();
+ // 获取参数类型
try {
- Method method = resolveMethodFromClass(service.getClass(), request.getMethod());
- Object result = method.invoke(service, request.getParams()); // dubbo, fastjson,
+ // 作业1:改成泛型和反射
+ // 先反射获取Class
+ Class> aClass = Class.forName(serviceClass);
+ // 通过 class 获取注入的bean,就可以实现去掉 @Bean(name = "XXX")中的name
+ Object service = resolver.resolve(aClass);//this.applicationContext.getBean(serviceClass);
+
+ Method method = aClass.getMethod(request.getMethod(),request.getParameterTypes());
+ // Method method = resolveMethodFromClass(service.getClass(), request.getMethod());
+ Object result = method.invoke(service, params); // dubbo, fastjson,
// 两次json序列化能否合并成一个
response.setResult(JSON.toJSONString(result, SerializerFeature.WriteClassName));
response.setStatus(true);
return response;
- } catch ( IllegalAccessException | InvocationTargetException e) {
+ } catch (IllegalAccessException | InvocationTargetException | ClassNotFoundException | NoSuchMethodException e) {
// 3.Xstream
@@ -45,6 +51,13 @@ public RpcfxResponse invoke(RpcfxRequest request) {
}
}
+ /**
+ * 此处使用反射替换
+ *
+ * @param klass
+ * @param methodName
+ * @return
+ */
private Method resolveMethodFromClass(Class> klass, String methodName) {
return Arrays.stream(klass.getMethods()).filter(m -> methodName.equals(m.getName())).findFirst().get();
}
diff --git a/07rpc/rpc01/rpcfx-demo-api/src/main/java/io/kimmking/rpcfx/demo/api/Order.java b/07rpc/rpc01/rpcfx-demo-api/src/main/java/io/kimmking/rpcfx/demo/api/Order.java
index a2fd6c91..bdb3ed0d 100644
--- a/07rpc/rpc01/rpcfx-demo-api/src/main/java/io/kimmking/rpcfx/demo/api/Order.java
+++ b/07rpc/rpc01/rpcfx-demo-api/src/main/java/io/kimmking/rpcfx/demo/api/Order.java
@@ -8,6 +8,8 @@ public class Order {
private float amount;
+ public Order(){}
+
public Order(int id, String name, float amount) {
this.id = id;
this.name = name;
diff --git a/07rpc/rpc01/rpcfx-demo-consumer/src/main/java/io/kimmking/rpcfx/demo/consumer/RpcfxClientApplication.java b/07rpc/rpc01/rpcfx-demo-consumer/src/main/java/io/kimmking/rpcfx/demo/consumer/RpcfxClientApplication.java
index 17537bb9..f510d17e 100644
--- a/07rpc/rpc01/rpcfx-demo-consumer/src/main/java/io/kimmking/rpcfx/demo/consumer/RpcfxClientApplication.java
+++ b/07rpc/rpc01/rpcfx-demo-consumer/src/main/java/io/kimmking/rpcfx/demo/consumer/RpcfxClientApplication.java
@@ -1,12 +1,16 @@
package io.kimmking.rpcfx.demo.consumer;
-import io.kimmking.rpcfx.client.Rpcfx;
+import io.kimmking.rpcfx.client.RpcfxByteBuddy;
+import io.kimmking.rpcfx.client.RpcfxProxy;
import io.kimmking.rpcfx.demo.api.Order;
import io.kimmking.rpcfx.demo.api.OrderService;
import io.kimmking.rpcfx.demo.api.User;
import io.kimmking.rpcfx.demo.api.UserService;
+import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
+import javax.annotation.Resource;
+
@SpringBootApplication
public class RpcfxClientApplication {
@@ -14,23 +18,22 @@ public class RpcfxClientApplication {
// 三方库 lib
// nexus, userserivce -> userdao -> user
//
-
public static void main(String[] args) {
// UserService service = new xxx();
// service.findById
-
- UserService userService = Rpcfx.create(UserService.class, "http://localhost:8080/");
+ RpcfxProxy rpcfxProxy = new RpcfxByteBuddy();
+ UserService userService = rpcfxProxy.create(UserService.class, "http://localhost:8080/");
User user = userService.findById(1);
System.out.println("find user id=1 from server: " + user.getName());
- OrderService orderService = Rpcfx.create(OrderService.class, "http://localhost:8080/");
+ OrderService orderService = rpcfxProxy.create(OrderService.class, "http://localhost:8080/");
Order order = orderService.findOrderById(1992129);
System.out.println(String.format("find order name=%s, amount=%f",order.getName(),order.getAmount()));
// 新加一个OrderService
-// SpringApplication.run(RpcfxClientApplication.class, args);
+ // SpringApplication.run(RpcfxClientApplication.class, args);
}
}
diff --git a/07rpc/rpc01/rpcfx-demo-provider/src/main/java/io/kimmking/rpcfx/demo/provider/DemoResolver.java b/07rpc/rpc01/rpcfx-demo-provider/src/main/java/io/kimmking/rpcfx/demo/provider/DemoResolver.java
index 65cffbd2..517fb9df 100644
--- a/07rpc/rpc01/rpcfx-demo-provider/src/main/java/io/kimmking/rpcfx/demo/provider/DemoResolver.java
+++ b/07rpc/rpc01/rpcfx-demo-provider/src/main/java/io/kimmking/rpcfx/demo/provider/DemoResolver.java
@@ -1,10 +1,13 @@
package io.kimmking.rpcfx.demo.provider;
import io.kimmking.rpcfx.api.RpcfxResolver;
+import io.kimmking.rpcfx.demo.api.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
-public class DemoResolver implements RpcfxResolver, ApplicationContextAware {
+import java.util.Arrays;
+
+public class DemoResolver implements RpcfxResolver, ApplicationContextAware {
private ApplicationContext applicationContext;
@@ -14,7 +17,7 @@ public void setApplicationContext(ApplicationContext applicationContext) {
}
@Override
- public Object resolve(String serviceClass) {
- return this.applicationContext.getBean(serviceClass);
+ public T resolve(Class t) {
+ return this.applicationContext.getBean(t);
}
}
diff --git a/07rpc/rpc01/rpcfx-demo-provider/src/main/java/io/kimmking/rpcfx/demo/provider/RpcfxServerApplication.java b/07rpc/rpc01/rpcfx-demo-provider/src/main/java/io/kimmking/rpcfx/demo/provider/RpcfxServerApplication.java
index 266618de..5db9b3c5 100644
--- a/07rpc/rpc01/rpcfx-demo-provider/src/main/java/io/kimmking/rpcfx/demo/provider/RpcfxServerApplication.java
+++ b/07rpc/rpc01/rpcfx-demo-provider/src/main/java/io/kimmking/rpcfx/demo/provider/RpcfxServerApplication.java
@@ -42,12 +42,12 @@ public RpcfxResolver createResolver(){
// 能否去掉name
//
- @Bean(name = "io.kimmking.rpcfx.demo.api.UserService")
+ @Bean()
public UserService createUserService(){
return new UserServiceImpl();
}
- @Bean(name = "io.kimmking.rpcfx.demo.api.OrderService")
+ @Bean()
public OrderService createOrderService(){
return new OrderServiceImpl();
}
diff --git a/07rpc/rpc01/rpcfx-demo-provider/src/main/java/io/kimmking/rpcfx/demo/provider/UserServiceImpl.java b/07rpc/rpc01/rpcfx-demo-provider/src/main/java/io/kimmking/rpcfx/demo/provider/UserServiceImpl.java
index 5c37d60a..9052ad6b 100644
--- a/07rpc/rpc01/rpcfx-demo-provider/src/main/java/io/kimmking/rpcfx/demo/provider/UserServiceImpl.java
+++ b/07rpc/rpc01/rpcfx-demo-provider/src/main/java/io/kimmking/rpcfx/demo/provider/UserServiceImpl.java
@@ -2,6 +2,7 @@
import io.kimmking.rpcfx.demo.api.User;
import io.kimmking.rpcfx.demo.api.UserService;
+import org.springframework.core.annotation.Order;
public class UserServiceImpl implements UserService {
From 5b21e20defa5c3170ac50a815ee1579aab08c13c Mon Sep 17 00:00:00 2001
From: baifukuan <1152465358@qq.com>
Date: Fri, 18 Dec 2020 21:33:24 +0800
Subject: [PATCH 4/7] =?UTF-8?q?week09=20=E4=BD=9C=E4=B8=9A?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
07rpc/rpc01/rpcfx-core/pom.xml | 10 +++
.../io/kimmking/rpcfx/client/HttpClient.java | 5 ++
.../kimmking/rpcfx/client/RpcfxByteBuddy.java | 1 -
.../rpcfx/proxy/RpcfxInvocationHandler.java | 70 +++++++++++--------
.../kimmking/rpcfx/server/RpcfxInvoker.java | 2 +-
.../demo/consumer/RpcfxClientApplication.java | 6 +-
.../demo/provider/RpcfxServerApplication.java | 4 +-
7 files changed, 60 insertions(+), 38 deletions(-)
create mode 100644 07rpc/rpc01/rpcfx-core/src/main/java/io/kimmking/rpcfx/client/HttpClient.java
diff --git a/07rpc/rpc01/rpcfx-core/pom.xml b/07rpc/rpc01/rpcfx-core/pom.xml
index d258f4bf..ddd04964 100644
--- a/07rpc/rpc01/rpcfx-core/pom.xml
+++ b/07rpc/rpc01/rpcfx-core/pom.xml
@@ -56,6 +56,16 @@
byte-buddy
1.7.11
+
+ commons-logging
+ commons-logging
+ 1.2
+
+
+ org.projectlombok
+ lombok
+
+
diff --git a/07rpc/rpc01/rpcfx-core/src/main/java/io/kimmking/rpcfx/client/HttpClient.java b/07rpc/rpc01/rpcfx-core/src/main/java/io/kimmking/rpcfx/client/HttpClient.java
new file mode 100644
index 00000000..2b6c28a1
--- /dev/null
+++ b/07rpc/rpc01/rpcfx-core/src/main/java/io/kimmking/rpcfx/client/HttpClient.java
@@ -0,0 +1,5 @@
+package io.kimmking.rpcfx.client;
+
+public class HttpClient {
+
+}
diff --git a/07rpc/rpc01/rpcfx-core/src/main/java/io/kimmking/rpcfx/client/RpcfxByteBuddy.java b/07rpc/rpc01/rpcfx-core/src/main/java/io/kimmking/rpcfx/client/RpcfxByteBuddy.java
index b7bac635..821240d8 100644
--- a/07rpc/rpc01/rpcfx-core/src/main/java/io/kimmking/rpcfx/client/RpcfxByteBuddy.java
+++ b/07rpc/rpc01/rpcfx-core/src/main/java/io/kimmking/rpcfx/client/RpcfxByteBuddy.java
@@ -1,6 +1,5 @@
package io.kimmking.rpcfx.client;
-import com.alibaba.fastjson.parser.ParserConfig;
import io.kimmking.rpcfx.proxy.RpcfxInvocationHandler;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.implementation.InvocationHandlerAdapter;
diff --git a/07rpc/rpc01/rpcfx-core/src/main/java/io/kimmking/rpcfx/proxy/RpcfxInvocationHandler.java b/07rpc/rpc01/rpcfx-core/src/main/java/io/kimmking/rpcfx/proxy/RpcfxInvocationHandler.java
index 4d3d2500..d1c3a05a 100644
--- a/07rpc/rpc01/rpcfx-core/src/main/java/io/kimmking/rpcfx/proxy/RpcfxInvocationHandler.java
+++ b/07rpc/rpc01/rpcfx-core/src/main/java/io/kimmking/rpcfx/proxy/RpcfxInvocationHandler.java
@@ -14,27 +14,37 @@
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
-public class RpcfxInvocationHandler implements InvocationHandler {
+public class RpcfxInvocationHandler implements InvocationHandler {
- public static final MediaType JSONTYPE = MediaType.get("application/json; charset=utf-8");
+ public static final MediaType JSONTYPE = MediaType.get("application/json; charset=utf-8");
- private final Class> serviceClass;
- private final String url;
- public RpcfxInvocationHandler(Class serviceClass, String url) {
- this.serviceClass = serviceClass;
- this.url = url;
- ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
- }
+ private final Class> serviceClass;
+ private final String url;
- // 可以尝试,自己去写对象序列化,二进制还是文本的,,,rpcfx是xml自定义序列化、反序列化,json: code.google.com/p/rpcfx
- // int byte char float double long bool
- // [], data class
+ public RpcfxInvocationHandler(Class serviceClass, String url) {
+ this.serviceClass = serviceClass;
+ this.url = url;
+ ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
+ }
+
+ // 可以尝试,自己去写对象序列化,二进制还是文本的,,,rpcfx是xml自定义序列化、反序列化,json: code.google.com/p/rpcfx
+ // int byte char float double long bool
+ // [], data class
- @Override
- public Object invoke(Object proxy, Method method, Object[] params) throws Throwable {
- return invokePost(method, params);
- }
+ @Override
+ public Object invoke(Object proxy, Method method, Object[] params) throws Throwable {
+ return invokePost(method, params);
+ }
+
+ /**
+ * 执行请求
+ *
+ * @param method
+ * @param params
+ * @return
+ * @throws IOException
+ */
private Object invokePost(Method method, Object[] params) throws IOException {
RpcfxRequest request = new RpcfxRequest();
request.setServiceClass(this.serviceClass.getName());
@@ -51,18 +61,18 @@ private Object invokePost(Method method, Object[] params) throws IOException {
}
private RpcfxResponse post(RpcfxRequest req, String url) throws IOException {
- String reqJson = JSON.toJSONString(req);
- System.out.println("req json: "+reqJson);
+ String reqJson = JSON.toJSONString(req);
+ System.out.println("req json: " + reqJson);
- // 1.可以复用client
- // 2.尝试使用httpclient或者netty client
- OkHttpClient client = new OkHttpClient();
- final Request request = new Request.Builder()
- .url(url)
- .post(RequestBody.create(JSONTYPE, reqJson))
- .build();
- String respJson = client.newCall(request).execute().body().string();
- System.out.println("resp json: "+respJson);
- return JSON.parseObject(respJson, RpcfxResponse.class);
- }
- }
\ No newline at end of file
+ // 1.可以复用client
+ // 2.尝试使用httpclient或者netty client
+ OkHttpClient client = new OkHttpClient();
+ final Request request = new Request.Builder()
+ .url(url)
+ .post(RequestBody.create(JSONTYPE, reqJson))
+ .build();
+ String respJson = client.newCall(request).execute().body().string();
+ System.out.println("resp json: " + respJson);
+ return JSON.parseObject(respJson, RpcfxResponse.class);
+ }
+}
\ No newline at end of file
diff --git a/07rpc/rpc01/rpcfx-core/src/main/java/io/kimmking/rpcfx/server/RpcfxInvoker.java b/07rpc/rpc01/rpcfx-core/src/main/java/io/kimmking/rpcfx/server/RpcfxInvoker.java
index 1c62943a..66ea6aab 100644
--- a/07rpc/rpc01/rpcfx-core/src/main/java/io/kimmking/rpcfx/server/RpcfxInvoker.java
+++ b/07rpc/rpc01/rpcfx-core/src/main/java/io/kimmking/rpcfx/server/RpcfxInvoker.java
@@ -42,7 +42,7 @@ public RpcfxResponse invoke(RpcfxRequest request){
// 3.Xstream
- // 2.封装一个统一的RpcfxException
+ // 2.封装一个统一的 RpcfxException
// 客户端也需要判断异常
e.printStackTrace();
response.setException(e);
diff --git a/07rpc/rpc01/rpcfx-demo-consumer/src/main/java/io/kimmking/rpcfx/demo/consumer/RpcfxClientApplication.java b/07rpc/rpc01/rpcfx-demo-consumer/src/main/java/io/kimmking/rpcfx/demo/consumer/RpcfxClientApplication.java
index f510d17e..5e2fb350 100644
--- a/07rpc/rpc01/rpcfx-demo-consumer/src/main/java/io/kimmking/rpcfx/demo/consumer/RpcfxClientApplication.java
+++ b/07rpc/rpc01/rpcfx-demo-consumer/src/main/java/io/kimmking/rpcfx/demo/consumer/RpcfxClientApplication.java
@@ -20,14 +20,12 @@ public class RpcfxClientApplication {
//
public static void main(String[] args) {
- // UserService service = new xxx();
- // service.findById
RpcfxProxy rpcfxProxy = new RpcfxByteBuddy();
- UserService userService = rpcfxProxy.create(UserService.class, "http://localhost:8080/");
+ UserService userService = rpcfxProxy.create(UserService.class, "http://localhost:8082/");
User user = userService.findById(1);
System.out.println("find user id=1 from server: " + user.getName());
- OrderService orderService = rpcfxProxy.create(OrderService.class, "http://localhost:8080/");
+ OrderService orderService = rpcfxProxy.create(OrderService.class, "http://localhost:8082/");
Order order = orderService.findOrderById(1992129);
System.out.println(String.format("find order name=%s, amount=%f",order.getName(),order.getAmount()));
diff --git a/07rpc/rpc01/rpcfx-demo-provider/src/main/java/io/kimmking/rpcfx/demo/provider/RpcfxServerApplication.java b/07rpc/rpc01/rpcfx-demo-provider/src/main/java/io/kimmking/rpcfx/demo/provider/RpcfxServerApplication.java
index 5db9b3c5..72bef551 100644
--- a/07rpc/rpc01/rpcfx-demo-provider/src/main/java/io/kimmking/rpcfx/demo/provider/RpcfxServerApplication.java
+++ b/07rpc/rpc01/rpcfx-demo-provider/src/main/java/io/kimmking/rpcfx/demo/provider/RpcfxServerApplication.java
@@ -42,12 +42,12 @@ public RpcfxResolver createResolver(){
// 能否去掉name
//
- @Bean()
+ @Bean
public UserService createUserService(){
return new UserServiceImpl();
}
- @Bean()
+ @Bean
public OrderService createOrderService(){
return new OrderServiceImpl();
}
From 7c42f4a4d3f62beebbb5356a49d15599867a7f9a Mon Sep 17 00:00:00 2001
From: baifukuan <1152465358@qq.com>
Date: Tue, 16 Feb 2021 23:25:50 +0800
Subject: [PATCH 5/7] test
---
README.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/README.md b/README.md
index e6a677d6..a160fe8c 100644
--- a/README.md
+++ b/README.md
@@ -1,2 +1,2 @@
# JavaCourse
-JavaCourse
+JavaCourse baifukuan
\ No newline at end of file
From 251c0723a41c9404a4a798d3a7e760df5ab530ca Mon Sep 17 00:00:00 2001
From: baifukuan <1152465358@qq.com>
Date: Tue, 16 Feb 2021 23:56:03 +0800
Subject: [PATCH 6/7] modify
---
README.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/README.md b/README.md
index a160fe8c..227f93a4 100644
--- a/README.md
+++ b/README.md
@@ -1,2 +1,2 @@
# JavaCourse
-JavaCourse baifukuan
\ No newline at end of file
+JavaCourse
\ No newline at end of file
From 4c5a886ad82507ffb45666e07963342a7053fb50 Mon Sep 17 00:00:00 2001
From: baifukuan <1152465358@qq.com>
Date: Wed, 17 Feb 2021 00:00:29 +0800
Subject: [PATCH 7/7] readme
---
README.md | 4 +++-
1 file changed, 3 insertions(+), 1 deletion(-)
diff --git a/README.md b/README.md
index 227f93a4..ef7749ba 100644
--- a/README.md
+++ b/README.md
@@ -1,2 +1,4 @@
# JavaCourse
-JavaCourse
\ No newline at end of file
+JavaCourse
+
+学习笔记
\ No newline at end of file