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..3c08c7c6
--- /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.hibernate.validator.internal.util.stereotypes.ThreadSafe;
+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();
+ }
+}
diff --git a/04fx/java8/src/main/java/io/kimmking/java8/CollectionDemo.java b/04fx/java8/src/main/java/io/kimmking/java8/CollectionDemo.java
index 90670a12..a30c9dd8 100644
--- a/04fx/java8/src/main/java/io/kimmking/java8/CollectionDemo.java
+++ b/04fx/java8/src/main/java/io/kimmking/java8/CollectionDemo.java
@@ -11,10 +11,15 @@ public static void main(String[] args) throws IOException {
List list = Arrays.asList(4,2,3,5,1,2,2,7,6); // Arrays还可以包装stream
print(list);
+ // 正序
Collections.sort(list);
print(list);
+
+ // 倒序
Collections.reverse(list);
print(list);
+
+ // 随机排序
Collections.shuffle(list);
print(list);
@@ -24,7 +29,7 @@ public static void main(String[] args) throws IOException {
Collections.fill(list,8);
print(list);
- list = Collections.singletonList(6);
+ list = Collections.singletonList(9);
print(list);
}
diff --git a/04fx/java8/src/main/resources/log4j.xml b/04fx/java8/src/main/resources/log4j.xml
index efc1f4f6..e7cd58b8 100644
--- a/04fx/java8/src/main/resources/log4j.xml
+++ b/04fx/java8/src/main/resources/log4j.xml
@@ -20,7 +20,7 @@
-
+
diff --git a/07rpc/rpc01/rpcfx-core/pom.xml b/07rpc/rpc01/rpcfx-core/pom.xml
index 4570a59d..d70df241 100644
--- a/07rpc/rpc01/rpcfx-core/pom.xml
+++ b/07rpc/rpc01/rpcfx-core/pom.xml
@@ -70,6 +70,21 @@
-
+
+ net.bytebuddy
+ 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/api/RpcfxRequest.java b/07rpc/rpc01/rpcfx-core/src/main/java/io/kimmking/rpcfx/api/RpcfxRequest.java
index 5ee7b9e1..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
@@ -1,10 +1,44 @@
package io.kimmking.rpcfx.api;
-import lombok.Data;
-
-@Data
public class RpcfxRequest {
+
private String serviceClass;
+
private String method;
+
private Object[] params;
+
+ private Class>[] parameterTypes;
+
+ public String getServiceClass() {
+ return serviceClass;
+ }
+
+ public void setServiceClass(String serviceClass) {
+ this.serviceClass = serviceClass;
+ }
+
+ public String getMethod() {
+ return method;
+ }
+
+ public void setMethod(String method) {
+ this.method = method;
+ }
+
+ public Object[] getParams() {
+ return params;
+ }
+
+ 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/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/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/Rpcfx.java b/07rpc/rpc01/rpcfx-core/src/main/java/io/kimmking/rpcfx/client/Rpcfx.java
index 74adbcc6..3d7b3788 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/client/Rpcfx.java
@@ -3,7 +3,8 @@
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.ParserConfig;
-import io.kimmking.rpcfx.api.*;
+import io.kimmking.rpcfx.api.RpcfxRequest;
+import io.kimmking.rpcfx.api.RpcfxResponse;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
@@ -13,8 +14,6 @@
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
-import java.util.ArrayList;
-import java.util.List;
public final class Rpcfx {
@@ -22,27 +21,10 @@ public final class Rpcfx {
ParserConfig.getGlobalInstance().addAccept("io.kimmking");
}
- public static T createFromRegistry(final Class serviceClass, final String zkUrl, Router router, LoadBalancer loadBalance, Filter filter) {
-
- // 加filte之一
-
- // curator Provider list from zk
- List invokers = new ArrayList<>();
- // 1. 简单:从zk拿到服务提供的列表
- // 2. 挑战:监听zk的临时节点,根据事件更新这个list(注意,需要做个全局map保持每个服务的提供者List)
-
- List urls = router.route(invokers);
-
- String url = loadBalance.select(urls); // router, loadbalance
-
- return (T) create(serviceClass, url, filter);
-
- }
-
- public static T create(final Class serviceClass, final String url, Filter... filters) {
+ 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, filters));
+ return (T) Proxy.newProxyInstance(Rpcfx.class.getClassLoader(), new Class[]{serviceClass}, new RpcfxInvocationHandler(serviceClass, url));
}
@@ -52,12 +34,9 @@ public static class RpcfxInvocationHandler implements InvocationHandler {
private final Class> serviceClass;
private final String url;
- private final Filter[] filters;
-
- public RpcfxInvocationHandler(Class serviceClass, String url, Filter... filters) {
+ public RpcfxInvocationHandler(Class serviceClass, String url) {
this.serviceClass = serviceClass;
this.url = url;
- this.filters = filters;
}
// 可以尝试,自己去写对象序列化,二进制还是文本的,,,rpcfx是xml自定义序列化、反序列化,json: code.google.com/p/rpcfx
@@ -66,28 +45,13 @@ public RpcfxInvocationHandler(Class serviceClass, String url, Filter... f
@Override
public Object invoke(Object proxy, Method method, Object[] params) throws Throwable {
-
- // 加filter地方之二
- // mock == true, new Student("hubao");
-
RpcfxRequest request = new RpcfxRequest();
request.setServiceClass(this.serviceClass.getName());
request.setMethod(method.getName());
request.setParams(params);
- if (null!=filters) {
- for (Filter filter : filters) {
- if (!filter.filter(request)) {
- return null;
- }
- }
- }
-
RpcfxResponse response = post(request, url);
- // 加filter地方之三
- // Student.setTeacher("cuijing");
-
// 这里判断response.status,处理异常
// 考虑封装一个全局的RpcfxException
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..821240d8
--- /dev/null
+++ b/07rpc/rpc01/rpcfx-core/src/main/java/io/kimmking/rpcfx/client/RpcfxByteBuddy.java
@@ -0,0 +1,39 @@
+package io.kimmking.rpcfx.client;
+
+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/proxy/RpcfxInvocationHandler.java b/07rpc/rpc01/rpcfx-core/src/main/java/io/kimmking/rpcfx/proxy/RpcfxInvocationHandler.java
new file mode 100644
index 00000000..d1c3a05a
--- /dev/null
+++ b/07rpc/rpc01/rpcfx-core/src/main/java/io/kimmking/rpcfx/proxy/RpcfxInvocationHandler.java
@@ -0,0 +1,78 @@
+package io.kimmking.rpcfx.proxy;
+
+import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.parser.ParserConfig;
+import io.kimmking.rpcfx.api.RpcfxRequest;
+import io.kimmking.rpcfx.api.RpcfxResponse;
+import okhttp3.MediaType;
+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;
+
+public class RpcfxInvocationHandler implements InvocationHandler {
+
+ 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);
+ }
+
+ // 可以尝试,自己去写对象序列化,二进制还是文本的,,,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);
+ }
+
+
+ /**
+ * 执行请求
+ *
+ * @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());
+ request.setMethod(method.getName());
+ request.setParams(params);
+ request.setParameterTypes(method.getParameterTypes());
+
+ RpcfxResponse response = post(request, url);
+
+ // 这里判断response.status,处理异常
+ // 考虑封装一个全局的RpcfxException
+
+ 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);
+
+ // 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 a6f77dac..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
@@ -14,29 +14,35 @@ 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
- // 2.封装一个统一的RpcfxException
+ // 2.封装一个统一的 RpcfxException
// 客户端也需要判断异常
e.printStackTrace();
response.setException(e);
@@ -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 b6371f0d..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
@@ -1,19 +1,15 @@
package io.kimmking.rpcfx.demo.consumer;
-import io.kimmking.rpcfx.api.Filter;
-import io.kimmking.rpcfx.api.LoadBalancer;
-import io.kimmking.rpcfx.api.Router;
-import io.kimmking.rpcfx.api.RpcfxRequest;
-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 lombok.extern.slf4j.Slf4j;
+import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
-import java.util.List;
-import java.util.Random;
+import javax.annotation.Resource;
@SpringBootApplication
public class RpcfxClientApplication {
@@ -22,49 +18,20 @@ 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:8082/");
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:8082/");
Order order = orderService.findOrderById(1992129);
System.out.println(String.format("find order name=%s, amount=%f",order.getName(),order.getAmount()));
- //
- UserService userService2 = Rpcfx.createFromRegistry(UserService.class, "localhost:2181", new TagRouter(), new RandomLoadBalancer(), new CuicuiFilter());
-
-// SpringApplication.run(RpcfxClientApplication.class, args);
- }
-
- private static class TagRouter implements Router {
- @Override
- public List route(List urls) {
- return urls;
- }
- }
+ // 新加一个OrderService
- private static class RandomLoadBalancer implements LoadBalancer {
- @Override
- public String select(List urls) {
- return urls.get(0);
- }
+ // SpringApplication.run(RpcfxClientApplication.class, args);
}
- @Slf4j
- private static class CuicuiFilter implements Filter {
- @Override
- public boolean filter(RpcfxRequest request) {
- log.info("filter {} -> {}", this.getClass().getName(), request.toString());
- return true;
- }
- }
}
-
-
-
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 f29a6d9d..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
@@ -1,18 +1,11 @@
package io.kimmking.rpcfx.demo.provider;
-import com.alibaba.fastjson.JSON;
import io.kimmking.rpcfx.api.RpcfxRequest;
import io.kimmking.rpcfx.api.RpcfxResolver;
import io.kimmking.rpcfx.api.RpcfxResponse;
-import io.kimmking.rpcfx.api.ServiceProviderDesc;
import io.kimmking.rpcfx.demo.api.OrderService;
import io.kimmking.rpcfx.demo.api.UserService;
import io.kimmking.rpcfx.server.RpcfxInvoker;
-import org.apache.curator.RetryPolicy;
-import org.apache.curator.framework.CuratorFramework;
-import org.apache.curator.framework.CuratorFrameworkFactory;
-import org.apache.curator.retry.ExponentialBackoffRetry;
-import org.apache.zookeeper.CreateMode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@@ -21,54 +14,14 @@
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
-import java.net.InetAddress;
-import java.net.InterfaceAddress;
-import java.net.UnknownHostException;
-
@SpringBootApplication
@RestController
public class RpcfxServerApplication {
- public static void main(String[] args) throws Exception {
-
- // start zk client
- RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
- CuratorFramework client = CuratorFrameworkFactory.builder().connectString("localhost:2181").namespace("rpcfx").retryPolicy(retryPolicy).build();
- client.start();
-
-
- // register service
- // xxx "io.kimmking.rpcfx.demo.api.UserService"
-
- String userService = "io.kimking.rpcfx.demo.api.UserService";
- registerService(client, userService);
- String orderService = "io.kimking.rpcfx.demo.api.OrderService";
- registerService(client, orderService);
-
-
- // 进一步的优化,是在spring加载完成后,从里面拿到特定注解的bean,自动注册到zk
-
+ public static void main(String[] args) {
SpringApplication.run(RpcfxServerApplication.class, args);
}
- private static void registerService(CuratorFramework client, String service) throws Exception {
- ServiceProviderDesc userServiceSesc = ServiceProviderDesc.builder()
- .host(InetAddress.getLocalHost().getHostAddress())
- .port(8080).serviceClass(service).build();
- // String userServiceSescJson = JSON.toJSONString(userServiceSesc);
-
- try {
- if ( null == client.checkExists().forPath("/" + service)) {
- client.create().withMode(CreateMode.PERSISTENT).forPath("/" + service, "service".getBytes());
- }
- } catch (Exception ex) {
- ex.printStackTrace();
- }
-
- client.create().withMode(CreateMode.EPHEMERAL).
- forPath( "/" + service + "/" + userServiceSesc.getHost() + "_" + userServiceSesc.getPort(), "provider".getBytes());
- }
-
@Autowired
RpcfxInvoker invoker;
@@ -89,16 +42,12 @@ public RpcfxResolver createResolver(){
// 能否去掉name
//
-
- // annotation
-
-
- @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 {
diff --git a/README.md b/README.md
index e6a677d6..ef7749ba 100644
--- a/README.md
+++ b/README.md
@@ -1,2 +1,4 @@
# JavaCourse
-JavaCourse
+JavaCourse
+
+学习笔记
\ No newline at end of file