From d5d4719a6cf682ccabd293d2d2e4235c9e5ee6f1 Mon Sep 17 00:00:00 2001 From: crossoverJie Date: Sat, 7 Sep 2024 19:01:11 +0800 Subject: [PATCH 1/8] refactor-proxy-manager --- cim-common/pom.xml | 6 ++ .../cim/common/core/proxy/ProxyManager.java | 63 ++++++++++++------- .../cim/common/core/proxy/Request.java | 15 +++++ .../cim/common/util/HttpClient.java | 19 +++++- .../common/core/proxy/ProxyManagerTest.java | 38 +++++++++++ .../crossoverjie/cim/route/api/RouteApi.java | 2 + 6 files changed, 120 insertions(+), 23 deletions(-) create mode 100644 cim-common/src/main/java/com/crossoverjie/cim/common/core/proxy/Request.java create mode 100644 cim-common/src/test/java/com/crossoverjie/cim/common/core/proxy/ProxyManagerTest.java diff --git a/cim-common/pom.xml b/cim-common/pom.xml index 78308209..cb9420ad 100644 --- a/cim-common/pom.xml +++ b/cim-common/pom.xml @@ -64,6 +64,12 @@ junit + + org.junit.jupiter + junit-jupiter + test + + io.netty netty-all diff --git a/cim-common/src/main/java/com/crossoverjie/cim/common/core/proxy/ProxyManager.java b/cim-common/src/main/java/com/crossoverjie/cim/common/core/proxy/ProxyManager.java index 92726f5a..ae7101d8 100644 --- a/cim-common/src/main/java/com/crossoverjie/cim/common/core/proxy/ProxyManager.java +++ b/cim-common/src/main/java/com/crossoverjie/cim/common/core/proxy/ProxyManager.java @@ -1,5 +1,6 @@ package com.crossoverjie.cim.common.core.proxy; +import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.crossoverjie.cim.common.exception.CIMException; import com.crossoverjie.cim.common.util.HttpClient; @@ -9,6 +10,7 @@ import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.net.URI; +import okhttp3.Response; import static com.crossoverjie.cim.common.enums.StatusEnum.VALIDATION_FAIL; @@ -22,16 +24,15 @@ public final class ProxyManager { - private Class clazz; + private final Class clazz; - private String url; + private final String url; - private OkHttpClient okHttpClient; + private final OkHttpClient okHttpClient; /** - * - * @param clazz Proxied interface - * @param url server provider url + * @param clazz Proxied interface + * @param url server provider url * @param okHttpClient http client */ public ProxyManager(Class clazz, String url, OkHttpClient okHttpClient) { @@ -40,12 +41,15 @@ public ProxyManager(Class clazz, String url, OkHttpClient okHttpClient) { this.okHttpClient = okHttpClient; } + /** * Get proxy instance of api. + * * @return */ public T getInstance() { - return (T) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[]{clazz}, new ProxyInvocation()); + return (T) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[]{clazz}, + new ProxyInvocation()); } @@ -53,25 +57,42 @@ private class ProxyInvocation implements InvocationHandler { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { - JSONObject jsonObject = new JSONObject(); - String serverUrl = url + "/" + method.getName() ; - URI serverUri = new URI(serverUrl); - serverUrl = serverUri.normalize().toString(); + Response result = null; + try { + Request annotation = method.getAnnotation(Request.class); + if (annotation != null && annotation.method().equals(Request.GET)) { + result = HttpClient.get(okHttpClient, url); + } else { + JSONObject jsonObject = new JSONObject(); + String serverUrl = url + "/" + method.getName(); + URI serverUri = new URI(serverUrl); + serverUrl = serverUri.normalize().toString(); - if (args != null && args.length > 1) { - throw new CIMException(VALIDATION_FAIL); - } + if (args != null && args.length > 1) { + throw new CIMException(VALIDATION_FAIL); + } - if (method.getParameterTypes().length > 0){ - Object para = args[0]; - Class parameterType = method.getParameterTypes()[0]; - for (Field field : parameterType.getDeclaredFields()) { - field.setAccessible(true); - jsonObject.put(field.getName(), field.get(para)); + if (method.getParameterTypes().length > 0) { + Object para = args[0]; + Class parameterType = method.getParameterTypes()[0]; + for (Field field : parameterType.getDeclaredFields()) { + field.setAccessible(true); + jsonObject.put(field.getName(), field.get(para)); + } + } + result = HttpClient.post(okHttpClient, jsonObject.toString(), serverUrl); + } + if (method.getReturnType() == void.class){ + return null; + } + String json = result.body().string(); + return JSON.parseObject(json, method.getReturnType()); + } finally { + if (result != null) { + result.body().close(); } } - return HttpClient.call(okHttpClient, jsonObject.toString(), serverUrl); } } } diff --git a/cim-common/src/main/java/com/crossoverjie/cim/common/core/proxy/Request.java b/cim-common/src/main/java/com/crossoverjie/cim/common/core/proxy/Request.java new file mode 100644 index 00000000..778a5b5c --- /dev/null +++ b/cim-common/src/main/java/com/crossoverjie/cim/common/core/proxy/Request.java @@ -0,0 +1,15 @@ +package com.crossoverjie.cim.common.core.proxy; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; + +/** + * @author crossoverJie + */ +@Retention(RetentionPolicy.RUNTIME) +public @interface Request { + String method() default POST; + + String GET = "GET"; + String POST = "POST"; +} diff --git a/cim-common/src/main/java/com/crossoverjie/cim/common/util/HttpClient.java b/cim-common/src/main/java/com/crossoverjie/cim/common/util/HttpClient.java index 3a80a1d7..32080a97 100644 --- a/cim-common/src/main/java/com/crossoverjie/cim/common/util/HttpClient.java +++ b/cim-common/src/main/java/com/crossoverjie/cim/common/util/HttpClient.java @@ -15,11 +15,11 @@ * Date: 2020-04-25 00:39 * @since JDK 1.8 */ -public final class HttpClient { +public final class HttpClient{ private static MediaType mediaType = MediaType.parse("application/json"); - public static Response call(OkHttpClient okHttpClient, String params, String url) throws IOException { + public static Response post(OkHttpClient okHttpClient, String params, String url) throws IOException { RequestBody requestBody = RequestBody.create(mediaType, params); Request request = new Request.Builder() @@ -34,4 +34,19 @@ public static Response call(OkHttpClient okHttpClient, String params, String url return response; } + + public static Response get(OkHttpClient okHttpClient, String url) throws IOException { + Request request = new Request.Builder() + .url(url) + .get() + .build(); + + Response response = okHttpClient.newCall(request).execute(); + if (!response.isSuccessful()) { + throw new IOException("Unexpected code " + response); + } + + return response; + } + } diff --git a/cim-common/src/test/java/com/crossoverjie/cim/common/core/proxy/ProxyManagerTest.java b/cim-common/src/test/java/com/crossoverjie/cim/common/core/proxy/ProxyManagerTest.java new file mode 100644 index 00000000..2cc401c9 --- /dev/null +++ b/cim-common/src/test/java/com/crossoverjie/cim/common/core/proxy/ProxyManagerTest.java @@ -0,0 +1,38 @@ +package com.crossoverjie.cim.common.core.proxy; + +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Data; +import lombok.NoArgsConstructor; +import okhttp3.OkHttpClient; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +class ProxyManagerTest { + + @Test + public void testGet() { + OkHttpClient client = new OkHttpClient(); + Github github = + new ProxyManager<>(Github.class, "https://api.github.com/users/crossoverjie", + client) + .getInstance(); + GithubResponse githubResponse = github.userInfo(); + Assertions.assertEquals(githubResponse.getName(), "crossoverJie"); + + github.userInfo2(); + } + + interface Github { + @Request(method = Request.GET) + GithubResponse userInfo(); + @Request(method = Request.GET) + void userInfo2(); + } + + @NoArgsConstructor + @Data + public static class GithubResponse { + @JsonProperty("name") + private String name; + } +} \ No newline at end of file diff --git a/cim-rout-api/src/main/java/com/crossoverjie/cim/route/api/RouteApi.java b/cim-rout-api/src/main/java/com/crossoverjie/cim/route/api/RouteApi.java index f6872ec3..cc1ec85f 100644 --- a/cim-rout-api/src/main/java/com/crossoverjie/cim/route/api/RouteApi.java +++ b/cim-rout-api/src/main/java/com/crossoverjie/cim/route/api/RouteApi.java @@ -1,5 +1,6 @@ package com.crossoverjie.cim.route.api; +import com.crossoverjie.cim.common.core.proxy.Request; import com.crossoverjie.cim.common.res.BaseResponse; import com.crossoverjie.cim.route.api.vo.req.ChatReqVO; import com.crossoverjie.cim.route.api.vo.req.LoginReqVO; @@ -66,6 +67,7 @@ public interface RouteApi { * @return * @throws Exception */ + @Request(method = Request.GET) Object onlineUser() throws Exception; // TODO: 2024/8/19 Get cache server & metastore server From 43130a9d0e87792e56e00f366ed53c0fbd1df3fa Mon Sep 17 00:00:00 2001 From: crossoverJie Date: Sun, 8 Sep 2024 00:03:18 +0800 Subject: [PATCH 2/8] refactor-proxy-manager --- README.md | 2 +- .../cim/client/client/CIMClient.java | 18 +- .../cim/client/config/BeanConfig.java | 6 +- .../client/controller/IndexController.java | 11 +- .../crossoverjie/cim/client/scanner/Scan.java | 2 + .../cim/client/service/InnerCommand.java | 2 +- .../cim/client/service/MsgHandle.java | 10 +- .../cim/client/service/RouteRequest.java | 23 +- .../cim/client/service/impl/MsgHandler.java | 19 +- .../client/service/impl/RouteRequestImpl.java | 145 ++++--------- .../impl/command/PrefixSearchCommand.java | 10 +- .../impl/command/PrintOnlineUsersCommand.java | 9 +- .../service/impl/command/ShutDownCommand.java | 6 +- .../cim/client/vo/req/GroupReqVO.java | 54 ----- .../cim/client/vo/req/LoginReqVO.java | 44 ---- .../cim/client/vo/req/P2PReqVO.java | 73 ------- .../cim/client/vo/req/SendMsgReqVO.java | 40 ---- .../cim/client/vo/res/CIMServerResVO.java | 111 ---------- .../cim/client/vo/res/OnlineUsersResVO.java | 84 -------- .../src/main/resources/application.yaml | 4 +- .../service/InnerCommandContextTest.java | 31 +-- .../cim/server/test/CommonTest.java | 148 +++++++++---- .../cim/server/test/RouteTest.java | 11 +- .../cim/common/core/proxy/ProxyManager.java | 98 --------- .../common/core/proxy/RpcProxyManager.java | 197 ++++++++++++++++++ .../cim/common/enums/StatusEnum.java | 2 +- .../cim/common/pojo/CIMUserInfo.java | 35 +--- .../cim/common/util/HttpClient.java | 2 +- ...agerTest.java => RpcProxyManagerTest.java} | 21 +- .../cim/route/controller/RouteController.java | 4 +- .../service/impl/AccountServiceRedisImpl.java | 20 +- .../crossoverjie/cim/client/ClientTest.java | 3 + .../crossoverjie/cim/route/api/RouteApi.java | 14 +- .../cim/route/api/vo/req/ChatReqVO.java | 31 +-- .../cim/route/api/vo/req/LoginReqVO.java | 2 + .../cim/route/api/vo/res/CIMServerResVO.java | 35 +--- .../cim/server/api/ServerApi.java | 4 +- .../cim/server/kit/RouteHandler.java | 9 +- 38 files changed, 483 insertions(+), 857 deletions(-) delete mode 100644 cim-client/src/main/java/com/crossoverjie/cim/client/vo/req/GroupReqVO.java delete mode 100644 cim-client/src/main/java/com/crossoverjie/cim/client/vo/req/LoginReqVO.java delete mode 100644 cim-client/src/main/java/com/crossoverjie/cim/client/vo/req/P2PReqVO.java delete mode 100644 cim-client/src/main/java/com/crossoverjie/cim/client/vo/req/SendMsgReqVO.java delete mode 100644 cim-client/src/main/java/com/crossoverjie/cim/client/vo/res/CIMServerResVO.java delete mode 100644 cim-client/src/main/java/com/crossoverjie/cim/client/vo/res/OnlineUsersResVO.java delete mode 100644 cim-common/src/main/java/com/crossoverjie/cim/common/core/proxy/ProxyManager.java create mode 100644 cim-common/src/main/java/com/crossoverjie/cim/common/core/proxy/RpcProxyManager.java rename cim-common/src/test/java/com/crossoverjie/cim/common/core/proxy/{ProxyManagerTest.java => RpcProxyManagerTest.java} (59%) diff --git a/README.md b/README.md index bbd4fa1d..f3edd3e8 100644 --- a/README.md +++ b/README.md @@ -108,7 +108,7 @@ 首先需要安装 `Zookeeper、Redis` 并保证网络通畅。 ```shell -docker run --name zookeeper -d -p 2181:2181 zookeeper: +docker run --rm --name zookeeper -d -p 2181:2181 zookeeper:3.9.2 docker run --rm --name redis -d -p 6379:6379 redis:7.4.0 ``` diff --git a/cim-client/src/main/java/com/crossoverjie/cim/client/client/CIMClient.java b/cim-client/src/main/java/com/crossoverjie/cim/client/client/CIMClient.java index 1bf4f19d..f1d8de25 100644 --- a/cim-client/src/main/java/com/crossoverjie/cim/client/client/CIMClient.java +++ b/cim-client/src/main/java/com/crossoverjie/cim/client/client/CIMClient.java @@ -8,8 +8,8 @@ import com.crossoverjie.cim.client.service.impl.ClientInfo; import com.crossoverjie.cim.client.thread.ContextHolder; import com.crossoverjie.cim.client.vo.req.GoogleProtocolVO; -import com.crossoverjie.cim.client.vo.req.LoginReqVO; -import com.crossoverjie.cim.client.vo.res.CIMServerResVO; +import com.crossoverjie.cim.route.api.vo.req.LoginReqVO; +import com.crossoverjie.cim.route.api.vo.res.CIMServerResVO; import com.crossoverjie.cim.common.constant.Constants; import com.crossoverjie.cim.common.protocol.CIMRequestProto; import io.netty.bootstrap.Bootstrap; @@ -22,15 +22,13 @@ import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.util.concurrent.DefaultThreadFactory; +import jakarta.annotation.PostConstruct; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; import org.springframework.stereotype.Component; -import jakarta.annotation.PostConstruct; - /** * Function: * @@ -79,7 +77,7 @@ public class CIMClient { public void start() throws Exception { //登录 + 获取可以使用的服务器 ip+port - CIMServerResVO.ServerInfo cimServer = userLogin(); + CIMServerResVO cimServer = userLogin(); //启动客户端 startClient(cimServer); @@ -96,7 +94,7 @@ public void start() throws Exception { * @param cimServer * @throws Exception */ - private void startClient(CIMServerResVO.ServerInfo cimServer) { + private void startClient(CIMServerResVO cimServer) { Bootstrap bootstrap = new Bootstrap(); bootstrap.group(group) .channel(NioSocketChannel.class) @@ -128,9 +126,9 @@ private void startClient(CIMServerResVO.ServerInfo cimServer) { * @return 路由服务器信息 * @throws Exception */ - private CIMServerResVO.ServerInfo userLogin() { + private CIMServerResVO userLogin() { LoginReqVO loginReqVO = new LoginReqVO(userId, userName); - CIMServerResVO.ServerInfo cimServer = null; + CIMServerResVO cimServer = null; try { cimServer = routeRequest.getCIMServer(loginReqVO); @@ -138,7 +136,7 @@ private CIMServerResVO.ServerInfo userLogin() { clientInfo.saveServiceInfo(cimServer.getIp() + ":" + cimServer.getCimServerPort()) .saveUserInfo(userId, userName); - log.info("cimServer=[{}]", cimServer.toString()); + log.info("cimServer=[{}]", cimServer); } catch (Exception e) { errorCount++; diff --git a/cim-client/src/main/java/com/crossoverjie/cim/client/config/BeanConfig.java b/cim-client/src/main/java/com/crossoverjie/cim/client/config/BeanConfig.java index ef1d488b..e86e9697 100644 --- a/cim-client/src/main/java/com/crossoverjie/cim/client/config/BeanConfig.java +++ b/cim-client/src/main/java/com/crossoverjie/cim/client/config/BeanConfig.java @@ -55,9 +55,9 @@ public CIMRequestProto.CIMReqProtocol heartBeat() { @Bean public OkHttpClient okHttpClient() { OkHttpClient.Builder builder = new OkHttpClient.Builder(); - builder.connectTimeout(30, TimeUnit.SECONDS) - .readTimeout(10, TimeUnit.SECONDS) - .writeTimeout(10,TimeUnit.SECONDS) + builder.connectTimeout(3, TimeUnit.SECONDS) + .readTimeout(3, TimeUnit.SECONDS) + .writeTimeout(3,TimeUnit.SECONDS) .retryOnConnectionFailure(true); return builder.build(); } diff --git a/cim-client/src/main/java/com/crossoverjie/cim/client/controller/IndexController.java b/cim-client/src/main/java/com/crossoverjie/cim/client/controller/IndexController.java index 5f785971..5c250563 100644 --- a/cim-client/src/main/java/com/crossoverjie/cim/client/controller/IndexController.java +++ b/cim-client/src/main/java/com/crossoverjie/cim/client/controller/IndexController.java @@ -3,13 +3,12 @@ import com.crossoverjie.cim.client.client.CIMClient; import com.crossoverjie.cim.client.service.RouteRequest; import com.crossoverjie.cim.client.vo.req.GoogleProtocolVO; -import com.crossoverjie.cim.client.vo.req.GroupReqVO; -import com.crossoverjie.cim.client.vo.req.SendMsgReqVO; import com.crossoverjie.cim.client.vo.req.StringReqVO; import com.crossoverjie.cim.client.vo.res.SendMsgResVO; import com.crossoverjie.cim.common.enums.StatusEnum; import com.crossoverjie.cim.common.res.BaseResponse; import com.crossoverjie.cim.common.res.NULLBody; +import com.crossoverjie.cim.route.api.vo.req.ChatReqVO; import io.swagger.v3.oas.annotations.Operation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; @@ -93,17 +92,15 @@ public BaseResponse sendProtoBufMsg(@RequestBody GoogleProtocolVO goog /** * 群发消息 - * @param sendMsgReqVO + * @param chatReqVO * @return */ @Operation(summary = "群发消息") @RequestMapping(value = "sendGroupMsg",method = RequestMethod.POST) @ResponseBody - public BaseResponse sendGroupMsg(@RequestBody SendMsgReqVO sendMsgReqVO) throws Exception { + public BaseResponse sendGroupMsg(@RequestBody ChatReqVO chatReqVO) throws Exception { BaseResponse res = new BaseResponse(); - - GroupReqVO groupReqVO = new GroupReqVO(sendMsgReqVO.getUserId(),sendMsgReqVO.getMsg()) ; - routeRequest.sendGroupMsg(groupReqVO) ; + routeRequest.sendGroupMsg(chatReqVO) ; // TODO: 2024/5/30 metrics diff --git a/cim-client/src/main/java/com/crossoverjie/cim/client/scanner/Scan.java b/cim-client/src/main/java/com/crossoverjie/cim/client/scanner/Scan.java index 824bee0d..fbd07485 100644 --- a/cim-client/src/main/java/com/crossoverjie/cim/client/scanner/Scan.java +++ b/cim-client/src/main/java/com/crossoverjie/cim/client/scanner/Scan.java @@ -8,6 +8,7 @@ import com.vdurmont.emoji.EmojiParser; import java.util.Scanner; +import lombok.SneakyThrows; /** * Function: @@ -37,6 +38,7 @@ public Scan() { this.echoService = SpringBeanFactory.getBean(EchoService.class) ; } + @SneakyThrows @Override public void run() { Scanner sc = new Scanner(System.in); diff --git a/cim-client/src/main/java/com/crossoverjie/cim/client/service/InnerCommand.java b/cim-client/src/main/java/com/crossoverjie/cim/client/service/InnerCommand.java index 77b704d9..3ea54802 100644 --- a/cim-client/src/main/java/com/crossoverjie/cim/client/service/InnerCommand.java +++ b/cim-client/src/main/java/com/crossoverjie/cim/client/service/InnerCommand.java @@ -13,5 +13,5 @@ public interface InnerCommand { * 执行 * @param msg */ - void process(String msg) ; + void process(String msg) throws Exception; } diff --git a/cim-client/src/main/java/com/crossoverjie/cim/client/service/MsgHandle.java b/cim-client/src/main/java/com/crossoverjie/cim/client/service/MsgHandle.java index 8af1e805..7cd89be0 100644 --- a/cim-client/src/main/java/com/crossoverjie/cim/client/service/MsgHandle.java +++ b/cim-client/src/main/java/com/crossoverjie/cim/client/service/MsgHandle.java @@ -1,7 +1,7 @@ package com.crossoverjie.cim.client.service; -import com.crossoverjie.cim.client.vo.req.GroupReqVO; -import com.crossoverjie.cim.client.vo.req.P2PReqVO; +import com.crossoverjie.cim.route.api.vo.req.ChatReqVO; +import com.crossoverjie.cim.route.api.vo.req.P2PReqVO; /** * Function:消息处理器 @@ -23,7 +23,7 @@ public interface MsgHandle { * @param groupReqVO 群聊消息 其中的 userId 为发送者的 userID * @throws Exception */ - void groupChat(GroupReqVO groupReqVO) throws Exception ; + void groupChat(ChatReqVO groupReqVO) throws Exception ; /** * 私聊 @@ -47,13 +47,13 @@ public interface MsgHandle { * @param msg * @return 是否应当跳过当前消息(包含了":" 就需要跳过) */ - boolean innerCommand(String msg) ; + boolean innerCommand(String msg) throws Exception; /** * 关闭系统 */ - void shutdown() ; + void shutdown() throws Exception; /** * 开启 AI 模式 diff --git a/cim-client/src/main/java/com/crossoverjie/cim/client/service/RouteRequest.java b/cim-client/src/main/java/com/crossoverjie/cim/client/service/RouteRequest.java index 33286f4a..3abeb3e0 100644 --- a/cim-client/src/main/java/com/crossoverjie/cim/client/service/RouteRequest.java +++ b/cim-client/src/main/java/com/crossoverjie/cim/client/service/RouteRequest.java @@ -1,12 +1,11 @@ package com.crossoverjie.cim.client.service; -import com.crossoverjie.cim.client.vo.req.GroupReqVO; -import com.crossoverjie.cim.client.vo.req.LoginReqVO; -import com.crossoverjie.cim.client.vo.req.P2PReqVO; -import com.crossoverjie.cim.client.vo.res.CIMServerResVO; -import com.crossoverjie.cim.client.vo.res.OnlineUsersResVO; - -import java.util.List; +import com.crossoverjie.cim.common.pojo.CIMUserInfo; +import com.crossoverjie.cim.route.api.vo.req.ChatReqVO; +import com.crossoverjie.cim.route.api.vo.req.LoginReqVO; +import com.crossoverjie.cim.route.api.vo.req.P2PReqVO; +import com.crossoverjie.cim.route.api.vo.res.CIMServerResVO; +import java.util.Set; /** * Function: @@ -19,10 +18,10 @@ public interface RouteRequest { /** * 群发消息 - * @param groupReqVO 消息 + * @param chatReqVO 消息 * @throws Exception */ - void sendGroupMsg(GroupReqVO groupReqVO) throws Exception; + void sendGroupMsg(ChatReqVO chatReqVO) throws Exception; /** @@ -38,16 +37,16 @@ public interface RouteRequest { * @param loginReqVO * @throws Exception */ - CIMServerResVO.ServerInfo getCIMServer(LoginReqVO loginReqVO) throws Exception; + CIMServerResVO getCIMServer(LoginReqVO loginReqVO) throws Exception; /** * 获取所有在线用户 * @return * @throws Exception */ - List onlineUsers()throws Exception ; + Set onlineUsers()throws Exception ; - void offLine() ; + void offLine() throws Exception; } diff --git a/cim-client/src/main/java/com/crossoverjie/cim/client/service/impl/MsgHandler.java b/cim-client/src/main/java/com/crossoverjie/cim/client/service/impl/MsgHandler.java index a71ec1da..f9149b21 100644 --- a/cim-client/src/main/java/com/crossoverjie/cim/client/service/impl/MsgHandler.java +++ b/cim-client/src/main/java/com/crossoverjie/cim/client/service/impl/MsgHandler.java @@ -6,16 +6,15 @@ import com.crossoverjie.cim.client.service.MsgHandle; import com.crossoverjie.cim.client.service.MsgLogger; import com.crossoverjie.cim.client.service.RouteRequest; -import com.crossoverjie.cim.client.vo.req.GroupReqVO; -import com.crossoverjie.cim.client.vo.req.P2PReqVO; import com.crossoverjie.cim.common.util.StringUtil; -import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - +import com.crossoverjie.cim.route.api.vo.req.ChatReqVO; +import com.crossoverjie.cim.route.api.vo.req.P2PReqVO; import jakarta.annotation.Resource; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; /** * Function: @@ -78,7 +77,7 @@ private void normalChat(String msg) { } else { //群聊 - GroupReqVO groupReqVO = new GroupReqVO(configuration.getUserId(), msg); + ChatReqVO groupReqVO = new ChatReqVO(configuration.getUserId(), msg); try { groupChat(groupReqVO); } catch (Exception e) { @@ -102,7 +101,7 @@ private void aiChat(String msg) { } @Override - public void groupChat(GroupReqVO groupReqVO) throws Exception { + public void groupChat(ChatReqVO groupReqVO) throws Exception { routeRequest.sendGroupMsg(groupReqVO); } @@ -123,7 +122,7 @@ public boolean checkMsg(String msg) { } @Override - public boolean innerCommand(String msg) { + public boolean innerCommand(String msg) throws Exception { if (msg.startsWith(":")) { @@ -143,7 +142,7 @@ public boolean innerCommand(String msg) { * 关闭系统 */ @Override - public void shutdown() { + public void shutdown() throws Exception { log.info("系统关闭中。。。。"); routeRequest.offLine(); msgLogger.stop(); diff --git a/cim-client/src/main/java/com/crossoverjie/cim/client/service/impl/RouteRequestImpl.java b/cim-client/src/main/java/com/crossoverjie/cim/client/service/impl/RouteRequestImpl.java index 0cfe2462..8165ac60 100644 --- a/cim-client/src/main/java/com/crossoverjie/cim/client/service/impl/RouteRequestImpl.java +++ b/cim-client/src/main/java/com/crossoverjie/cim/client/service/impl/RouteRequestImpl.java @@ -1,35 +1,32 @@ package com.crossoverjie.cim.client.service.impl; -import com.alibaba.fastjson.JSON; import com.crossoverjie.cim.client.config.AppConfiguration; import com.crossoverjie.cim.client.service.EchoService; import com.crossoverjie.cim.client.service.RouteRequest; import com.crossoverjie.cim.client.thread.ContextHolder; -import com.crossoverjie.cim.client.vo.req.GroupReqVO; -import com.crossoverjie.cim.client.vo.req.LoginReqVO; -import com.crossoverjie.cim.client.vo.req.P2PReqVO; -import com.crossoverjie.cim.client.vo.res.CIMServerResVO; -import com.crossoverjie.cim.client.vo.res.OnlineUsersResVO; -import com.crossoverjie.cim.common.core.proxy.ProxyManager; +import com.crossoverjie.cim.common.core.proxy.RpcProxyManager; import com.crossoverjie.cim.common.enums.StatusEnum; import com.crossoverjie.cim.common.exception.CIMException; +import com.crossoverjie.cim.common.pojo.CIMUserInfo; import com.crossoverjie.cim.common.res.BaseResponse; +import com.crossoverjie.cim.common.res.NULLBody; import com.crossoverjie.cim.route.api.RouteApi; import com.crossoverjie.cim.route.api.vo.req.ChatReqVO; +import com.crossoverjie.cim.route.api.vo.req.LoginReqVO; +import com.crossoverjie.cim.route.api.vo.req.P2PReqVO; +import com.crossoverjie.cim.route.api.vo.res.CIMServerResVO; +import java.util.Set; import lombok.extern.slf4j.Slf4j; import okhttp3.OkHttpClient; -import okhttp3.Response; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; -import java.util.List; - /** * Function: * * @author crossoverJie - * Date: 2018/12/22 22:27 + * Date: 2018/12/22 22:27 * @since JDK 1.8 */ @Slf4j @@ -37,126 +34,68 @@ public class RouteRequestImpl implements RouteRequest { @Autowired - private OkHttpClient okHttpClient ; + private OkHttpClient okHttpClient; @Value("${cim.route.url}") - private String routeUrl ; + private String routeUrl; @Autowired - private EchoService echoService ; + private EchoService echoService; @Autowired - private AppConfiguration appConfiguration ; + private AppConfiguration appConfiguration; @Override - public void sendGroupMsg(GroupReqVO groupReqVO) throws Exception { - RouteApi routeApi = new ProxyManager<>(RouteApi.class, routeUrl, okHttpClient).getInstance(); - ChatReqVO chatReqVO = new ChatReqVO(groupReqVO.getUserId(), groupReqVO.getMsg()) ; - Response response = null; - try { - response = (Response)routeApi.groupRoute(chatReqVO); - }catch (Exception e){ - log.error("exception",e); - }finally { - response.body().close(); - } + public void sendGroupMsg(ChatReqVO chatReqVO) throws Exception { + RouteApi routeApi = RpcProxyManager.create(RouteApi.class, routeUrl, okHttpClient); + routeApi.groupRoute(chatReqVO); } @Override public void sendP2PMsg(P2PReqVO p2PReqVO) throws Exception { - RouteApi routeApi = new ProxyManager<>(RouteApi.class, routeUrl, okHttpClient).getInstance(); - com.crossoverjie.cim.route.api.vo.req.P2PReqVO vo = new com.crossoverjie.cim.route.api.vo.req.P2PReqVO() ; - vo.setMsg(p2PReqVO.getMsg()); - vo.setReceiveUserId(p2PReqVO.getReceiveUserId()); - vo.setUserId(p2PReqVO.getUserId()); - - Response response = null; - try { - response = (Response) routeApi.p2pRoute(vo); - String json = response.body().string() ; - BaseResponse baseResponse = JSON.parseObject(json, BaseResponse.class); - - // account offline. - if (baseResponse.getCode().equals(StatusEnum.OFF_LINE.getCode())){ - log.error(p2PReqVO.getReceiveUserId() + ":" + StatusEnum.OFF_LINE.getMessage()); - } - - }catch (Exception e){ - log.error("exception",e); - }finally { - response.body().close(); + RouteApi routeApi = RpcProxyManager.create(RouteApi.class, routeUrl, okHttpClient); + BaseResponse response = routeApi.p2pRoute(p2PReqVO); + // account offline. + if (response.getCode().equals(StatusEnum.OFF_LINE.getCode())) { + log.error(p2PReqVO.getReceiveUserId() + ":" + StatusEnum.OFF_LINE.getMessage()); } } @Override - public CIMServerResVO.ServerInfo getCIMServer(LoginReqVO loginReqVO) throws Exception { - - RouteApi routeApi = new ProxyManager<>(RouteApi.class, routeUrl, okHttpClient).getInstance(); - com.crossoverjie.cim.route.api.vo.req.LoginReqVO vo = new com.crossoverjie.cim.route.api.vo.req.LoginReqVO() ; - vo.setUserId(loginReqVO.getUserId()); - vo.setUserName(loginReqVO.getUserName()); - - Response response = null; - CIMServerResVO cimServerResVO = null; - try { - response = (Response) routeApi.login(vo); - String json = response.body().string(); - cimServerResVO = JSON.parseObject(json, CIMServerResVO.class); - - //重复失败 - if (!cimServerResVO.getCode().equals(StatusEnum.SUCCESS.getCode())){ - echoService.echo(cimServerResVO.getMessage()); - - // when client in reConnect state, could not exit. - if (ContextHolder.getReconnect()){ - echoService.echo("###{}###", StatusEnum.RECONNECT_FAIL.getMessage()); - throw new CIMException(StatusEnum.RECONNECT_FAIL); - } - - System.exit(-1); + public CIMServerResVO getCIMServer(LoginReqVO loginReqVO) throws Exception { + + RouteApi routeApi = RpcProxyManager.create(RouteApi.class, routeUrl, okHttpClient); + BaseResponse cimServerResVO = routeApi.login(loginReqVO); + + // repeat fail + if (!cimServerResVO.getCode().equals(StatusEnum.SUCCESS.getCode())) { + echoService.echo(cimServerResVO.getMessage()); + + // when client in reConnect state, could not exit. + if (ContextHolder.getReconnect()) { + echoService.echo("###{}###", StatusEnum.RECONNECT_FAIL.getMessage()); + throw new CIMException(StatusEnum.RECONNECT_FAIL); } - }catch (Exception e){ - log.error("exception",e); - }finally { - response.body().close(); + System.exit(-1); } + return cimServerResVO.getDataBody(); } @Override - public List onlineUsers() throws Exception{ - RouteApi routeApi = new ProxyManager<>(RouteApi.class, routeUrl, okHttpClient).getInstance(); - - Response response = null; - OnlineUsersResVO onlineUsersResVO = null; - try { - response = (Response) routeApi.onlineUser(); - String json = response.body().string() ; - onlineUsersResVO = JSON.parseObject(json, OnlineUsersResVO.class); - - }catch (Exception e){ - log.error("exception",e); - }finally { - response.body().close(); - } - + public Set onlineUsers() throws Exception { + RouteApi routeApi = RpcProxyManager.create(RouteApi.class, routeUrl, okHttpClient); + BaseResponse> onlineUsersResVO = routeApi.onlineUser(); return onlineUsersResVO.getDataBody(); } @Override - public void offLine() { - RouteApi routeApi = new ProxyManager<>(RouteApi.class, routeUrl, okHttpClient).getInstance(); - ChatReqVO vo = new ChatReqVO(appConfiguration.getUserId(), "offLine") ; - Response response = null; - try { - response = (Response) routeApi.offLine(vo); - } catch (Exception e) { - log.error("exception",e); - } finally { - response.body().close(); - } + public void offLine() throws Exception { + RouteApi routeApi = RpcProxyManager.create(RouteApi.class, routeUrl, okHttpClient); + ChatReqVO vo = new ChatReqVO(appConfiguration.getUserId(), "offLine"); + routeApi.offLine(vo); } } diff --git a/cim-client/src/main/java/com/crossoverjie/cim/client/service/impl/command/PrefixSearchCommand.java b/cim-client/src/main/java/com/crossoverjie/cim/client/service/impl/command/PrefixSearchCommand.java index e3270a9b..ab1a06e8 100644 --- a/cim-client/src/main/java/com/crossoverjie/cim/client/service/impl/command/PrefixSearchCommand.java +++ b/cim-client/src/main/java/com/crossoverjie/cim/client/service/impl/command/PrefixSearchCommand.java @@ -3,14 +3,14 @@ import com.crossoverjie.cim.client.service.EchoService; import com.crossoverjie.cim.client.service.InnerCommand; import com.crossoverjie.cim.client.service.RouteRequest; -import com.crossoverjie.cim.client.vo.res.OnlineUsersResVO; import com.crossoverjie.cim.common.data.construct.TrieTree; +import com.crossoverjie.cim.common.pojo.CIMUserInfo; +import java.util.List; +import java.util.Set; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; -import java.util.List; - /** * Function: * @@ -31,9 +31,9 @@ public class PrefixSearchCommand implements InnerCommand { @Override public void process(String msg) { try { - List onlineUsers = routeRequest.onlineUsers(); + Set onlineUsers = routeRequest.onlineUsers(); TrieTree trieTree = new TrieTree(); - for (OnlineUsersResVO.DataBodyBean onlineUser : onlineUsers) { + for (CIMUserInfo onlineUser : onlineUsers) { trieTree.insert(onlineUser.getUserName()); } diff --git a/cim-client/src/main/java/com/crossoverjie/cim/client/service/impl/command/PrintOnlineUsersCommand.java b/cim-client/src/main/java/com/crossoverjie/cim/client/service/impl/command/PrintOnlineUsersCommand.java index b015f0c7..4fe9992b 100644 --- a/cim-client/src/main/java/com/crossoverjie/cim/client/service/impl/command/PrintOnlineUsersCommand.java +++ b/cim-client/src/main/java/com/crossoverjie/cim/client/service/impl/command/PrintOnlineUsersCommand.java @@ -3,13 +3,12 @@ import com.crossoverjie.cim.client.service.EchoService; import com.crossoverjie.cim.client.service.InnerCommand; import com.crossoverjie.cim.client.service.RouteRequest; -import com.crossoverjie.cim.client.vo.res.OnlineUsersResVO; +import com.crossoverjie.cim.common.pojo.CIMUserInfo; +import java.util.Set; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; -import java.util.List; - /** * Function: * @@ -30,10 +29,10 @@ public class PrintOnlineUsersCommand implements InnerCommand { @Override public void process(String msg) { try { - List onlineUsers = routeRequest.onlineUsers(); + Set onlineUsers = routeRequest.onlineUsers(); echoService.echo("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); - for (OnlineUsersResVO.DataBodyBean onlineUser : onlineUsers) { + for (CIMUserInfo onlineUser : onlineUsers) { echoService.echo("userId={}=====userName={}",onlineUser.getUserId(),onlineUser.getUserName()); } echoService.echo("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); diff --git a/cim-client/src/main/java/com/crossoverjie/cim/client/service/impl/command/ShutDownCommand.java b/cim-client/src/main/java/com/crossoverjie/cim/client/service/impl/command/ShutDownCommand.java index 6c05a4ba..758187ec 100644 --- a/cim-client/src/main/java/com/crossoverjie/cim/client/service/impl/command/ShutDownCommand.java +++ b/cim-client/src/main/java/com/crossoverjie/cim/client/service/impl/command/ShutDownCommand.java @@ -51,7 +51,7 @@ public class ShutDownCommand implements InnerCommand { private RingBufferWheel ringBufferWheel ; @Override - public void process(String msg) { + public void process(String msg) throws Exception { echoService.echo("cim client closing..."); shutDownMsg.shutdown(); routeRequest.offLine(); @@ -63,8 +63,8 @@ public void process(String msg) { echoService.echo("thread pool closing"); } cimClient.close(); - } catch (InterruptedException e) { - log.error("InterruptedException", e); + } catch (Exception e) { + log.error("exception", e); } echoService.echo("cim close success!"); System.exit(0); diff --git a/cim-client/src/main/java/com/crossoverjie/cim/client/vo/req/GroupReqVO.java b/cim-client/src/main/java/com/crossoverjie/cim/client/vo/req/GroupReqVO.java deleted file mode 100644 index c9d2145e..00000000 --- a/cim-client/src/main/java/com/crossoverjie/cim/client/vo/req/GroupReqVO.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.crossoverjie.cim.client.vo.req; - -import com.crossoverjie.cim.common.req.BaseRequest; - -import io.swagger.v3.oas.annotations.media.Schema; -import jakarta.validation.constraints.NotNull; - -/** - * Function: 群发请求 - * - * @author crossoverJie - * Date: 2018/05/21 15:56 - * @since JDK 1.8 - */ -public class GroupReqVO extends BaseRequest { - - @NotNull(message = "userId 不能为空") - @Schema(requiredMode = Schema.RequiredMode.REQUIRED, description = "消息发送者的 userId", example = "1545574049323") - private Long userId ; - - - @NotNull(message = "msg 不能为空") - @Schema(requiredMode = Schema.RequiredMode.REQUIRED, description = "msg", example = "hello") - private String msg ; - - public GroupReqVO(Long userId, String msg) { - this.userId = userId; - this.msg = msg; - } - - public String getMsg() { - return msg; - } - - public void setMsg(String msg) { - this.msg = msg; - } - - public Long getUserId() { - return userId; - } - - public void setUserId(Long userId) { - this.userId = userId; - } - - @Override - public String toString() { - return "GroupReqVO{" + - "userId=" + userId + - ", msg='" + msg + '\'' + - "} " + super.toString(); - } -} diff --git a/cim-client/src/main/java/com/crossoverjie/cim/client/vo/req/LoginReqVO.java b/cim-client/src/main/java/com/crossoverjie/cim/client/vo/req/LoginReqVO.java deleted file mode 100644 index 66de629e..00000000 --- a/cim-client/src/main/java/com/crossoverjie/cim/client/vo/req/LoginReqVO.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.crossoverjie.cim.client.vo.req; - -import com.crossoverjie.cim.common.req.BaseRequest; - -/** - * Function: - * - * @author crossoverJie - * Date: 2018/12/23 22:30 - * @since JDK 1.8 - */ -public class LoginReqVO extends BaseRequest{ - private Long userId ; - private String userName ; - - public LoginReqVO(Long userId, String userName) { - this.userId = userId; - this.userName = userName; - } - - public Long getUserId() { - return userId; - } - - public void setUserId(Long userId) { - this.userId = userId; - } - - public String getUserName() { - return userName; - } - - public void setUserName(String userName) { - this.userName = userName; - } - - @Override - public String toString() { - return "LoginReqVO{" + - "userId=" + userId + - ", userName='" + userName + '\'' + - "} " + super.toString(); - } -} diff --git a/cim-client/src/main/java/com/crossoverjie/cim/client/vo/req/P2PReqVO.java b/cim-client/src/main/java/com/crossoverjie/cim/client/vo/req/P2PReqVO.java deleted file mode 100644 index 7b66dc41..00000000 --- a/cim-client/src/main/java/com/crossoverjie/cim/client/vo/req/P2PReqVO.java +++ /dev/null @@ -1,73 +0,0 @@ -package com.crossoverjie.cim.client.vo.req; - -import com.crossoverjie.cim.common.req.BaseRequest; - -import io.swagger.v3.oas.annotations.media.Schema; -import jakarta.validation.constraints.NotNull; - -/** - * Function: 单聊请求 - * - * @author crossoverJie - * Date: 2018/05/21 15:56 - * @since JDK 1.8 - */ -public class P2PReqVO extends BaseRequest { - - @NotNull(message = "userId 不能为空") - @Schema(requiredMode = Schema.RequiredMode.REQUIRED , description = "消息发送者的 userId", example = "1545574049323") - private Long userId ; - - - @NotNull(message = "userId 不能为空") - @Schema(requiredMode = Schema.RequiredMode.REQUIRED , description = "消息接收者的 userId", example = "1545574049323") - private Long receiveUserId ; - - - - - @NotNull(message = "msg 不能为空") - @Schema(requiredMode = Schema.RequiredMode.REQUIRED , description = "msg", example = "hello") - private String msg ; - - public P2PReqVO() { - } - - public P2PReqVO(Long userId, Long receiveUserId, String msg) { - this.userId = userId; - this.receiveUserId = receiveUserId; - this.msg = msg; - } - - public Long getReceiveUserId() { - return receiveUserId; - } - - public void setReceiveUserId(Long receiveUserId) { - this.receiveUserId = receiveUserId; - } - - public String getMsg() { - return msg; - } - - public void setMsg(String msg) { - this.msg = msg; - } - - public Long getUserId() { - return userId; - } - - public void setUserId(Long userId) { - this.userId = userId; - } - - @Override - public String toString() { - return "GroupReqVO{" + - "userId=" + userId + - ", msg='" + msg + '\'' + - "} " + super.toString(); - } -} diff --git a/cim-client/src/main/java/com/crossoverjie/cim/client/vo/req/SendMsgReqVO.java b/cim-client/src/main/java/com/crossoverjie/cim/client/vo/req/SendMsgReqVO.java deleted file mode 100644 index 8fe4c8e1..00000000 --- a/cim-client/src/main/java/com/crossoverjie/cim/client/vo/req/SendMsgReqVO.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.crossoverjie.cim.client.vo.req; - -import com.crossoverjie.cim.common.req.BaseRequest; - -import io.swagger.v3.oas.annotations.media.Schema; -import jakarta.validation.constraints.NotNull; - -/** - * Function: - * - * @author crossoverJie - * Date: 2018/05/21 15:56 - * @since JDK 1.8 - */ -public class SendMsgReqVO extends BaseRequest { - - @NotNull(message = "msg 不能为空") - @Schema(requiredMode = Schema.RequiredMode.REQUIRED , description = "msg", example = "hello") - private String msg ; - - @NotNull(message = "userId 不能为空") - @Schema(requiredMode = Schema.RequiredMode.REQUIRED , description = "userId", example = "11") - private Long userId ; - - public String getMsg() { - return msg; - } - - public void setMsg(String msg) { - this.msg = msg; - } - - public long getUserId() { - return userId; - } - - public void setUserId(long userId) { - this.userId = userId; - } -} diff --git a/cim-client/src/main/java/com/crossoverjie/cim/client/vo/res/CIMServerResVO.java b/cim-client/src/main/java/com/crossoverjie/cim/client/vo/res/CIMServerResVO.java deleted file mode 100644 index 5382ea26..00000000 --- a/cim-client/src/main/java/com/crossoverjie/cim/client/vo/res/CIMServerResVO.java +++ /dev/null @@ -1,111 +0,0 @@ -package com.crossoverjie.cim.client.vo.res; - -import java.io.Serializable; - -/** - * Function: - * - * @author crossoverJie - * Date: 2018/12/23 00:43 - * @since JDK 1.8 - */ -public class CIMServerResVO implements Serializable { - - /** - * code : 9000 - * message : 成功 - * reqNo : null - * dataBody : {"ip":"127.0.0.1","port":8081} - */ - - private String code; - private String message; - private Object reqNo; - private ServerInfo dataBody; - - public String getCode() { - return code; - } - - public void setCode(String code) { - this.code = code; - } - - public String getMessage() { - return message; - } - - public void setMessage(String message) { - this.message = message; - } - - public Object getReqNo() { - return reqNo; - } - - public void setReqNo(Object reqNo) { - this.reqNo = reqNo; - } - - public ServerInfo getDataBody() { - return dataBody; - } - - public void setDataBody(ServerInfo dataBody) { - this.dataBody = dataBody; - } - - public static class ServerInfo { - /** - * ip : 127.0.0.1 - * port : 8081 - */ - private String ip ; - private Integer cimServerPort; - private Integer httpPort; - - public String getIp() { - return ip; - } - - public void setIp(String ip) { - this.ip = ip; - } - - public Integer getCimServerPort() { - return cimServerPort; - } - - public void setCimServerPort(Integer cimServerPort) { - this.cimServerPort = cimServerPort; - } - - public Integer getHttpPort() { - return httpPort; - } - - public void setHttpPort(Integer httpPort) { - this.httpPort = httpPort; - } - - @Override - public String toString() { - return "ServerInfo{" + - "ip='" + ip + '\'' + - ", cimServerPort=" + cimServerPort + - ", httpPort=" + httpPort + - '}'; - } - } - - - @Override - public String toString() { - return "CIMServerResVO{" + - "code='" + code + '\'' + - ", message='" + message + '\'' + - ", reqNo=" + reqNo + - ", dataBody=" + dataBody + - '}'; - } -} diff --git a/cim-client/src/main/java/com/crossoverjie/cim/client/vo/res/OnlineUsersResVO.java b/cim-client/src/main/java/com/crossoverjie/cim/client/vo/res/OnlineUsersResVO.java deleted file mode 100644 index 19658168..00000000 --- a/cim-client/src/main/java/com/crossoverjie/cim/client/vo/res/OnlineUsersResVO.java +++ /dev/null @@ -1,84 +0,0 @@ -package com.crossoverjie.cim.client.vo.res; - -import java.util.List; - -/** - * Function: - * - * @author crossoverJie - * Date: 2018/12/26 23:17 - * @since JDK 1.8 - */ -public class OnlineUsersResVO { - - - /** - * code : 9000 - * message : 成功 - * reqNo : null - * dataBody : [{"userId":1545574841528,"userName":"zhangsan"},{"userId":1545574871143,"userName":"crossoverJie"}] - */ - - private String code; - private String message; - private Object reqNo; - private List dataBody; - - public String getCode() { - return code; - } - - public void setCode(String code) { - this.code = code; - } - - public String getMessage() { - return message; - } - - public void setMessage(String message) { - this.message = message; - } - - public Object getReqNo() { - return reqNo; - } - - public void setReqNo(Object reqNo) { - this.reqNo = reqNo; - } - - public List getDataBody() { - return dataBody; - } - - public void setDataBody(List dataBody) { - this.dataBody = dataBody; - } - - public static class DataBodyBean { - /** - * userId : 1545574841528 - * userName : zhangsan - */ - - private long userId; - private String userName; - - public long getUserId() { - return userId; - } - - public void setUserId(long userId) { - this.userId = userId; - } - - public String getUserName() { - return userName; - } - - public void setUserName(String userName) { - this.userName = userName; - } - } -} diff --git a/cim-client/src/main/resources/application.yaml b/cim-client/src/main/resources/application.yaml index f1b92859..d1d3e495 100644 --- a/cim-client/src/main/resources/application.yaml +++ b/cim-client/src/main/resources/application.yaml @@ -23,8 +23,8 @@ cim: route: url: http://localhost:8083 # route url suggested that this is Nginx address user: # cim userId and userName - id: 1722343979085 - userName: zhangsan + id: 1725714450795 + userName: cj4 callback: thread: queue: diff --git a/cim-client/src/test/java/com/crossoverjie/cim/client/service/InnerCommandContextTest.java b/cim-client/src/test/java/com/crossoverjie/cim/client/service/InnerCommandContextTest.java index bd9b7e23..6bfc1463 100644 --- a/cim-client/src/test/java/com/crossoverjie/cim/client/service/InnerCommandContextTest.java +++ b/cim-client/src/test/java/com/crossoverjie/cim/client/service/InnerCommandContextTest.java @@ -1,9 +1,16 @@ package com.crossoverjie.cim.client.service; +import com.alibaba.fastjson.JSONObject; import com.crossoverjie.cim.client.CIMClientApplication; -import com.crossoverjie.cim.client.service.InnerCommand; -import com.crossoverjie.cim.client.service.InnerCommandContext; +import com.crossoverjie.cim.common.core.proxy.RpcProxyManager; import com.crossoverjie.cim.common.enums.SystemCommandEnum; +import com.crossoverjie.cim.common.res.BaseResponse; +import com.crossoverjie.cim.route.api.RouteApi; +import com.crossoverjie.cim.route.api.vo.req.LoginReqVO; +import com.crossoverjie.cim.route.api.vo.res.CIMServerResVO; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import okhttp3.OkHttpClient; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -18,14 +25,14 @@ public class InnerCommandContextTest { private InnerCommandContext context; @Test - public void execute() { + public void execute() throws Exception { String msg = ":all"; InnerCommand execute = context.getInstance(msg); execute.process(msg) ; } // @Test - public void execute3() { + public void execute3() throws Exception { // TODO: 2024/8/31 Integration test String msg = SystemCommandEnum.ONLINE_USER.getCommandType(); InnerCommand execute = context.getInstance(msg); @@ -33,35 +40,35 @@ public void execute3() { } @Test - public void execute4() { + public void execute4() throws Exception { String msg = ":q 天气"; InnerCommand execute = context.getInstance(msg); execute.process(msg) ; } @Test - public void execute5() { + public void execute5() throws Exception { String msg = ":q crossoverJie"; InnerCommand execute = context.getInstance(msg); execute.process(msg) ; } @Test - public void execute6() { + public void execute6() throws Exception { String msg = SystemCommandEnum.AI.getCommandType(); InnerCommand execute = context.getInstance(msg); execute.process(msg) ; } @Test - public void execute7() { + public void execute7() throws Exception { String msg = SystemCommandEnum.QAI.getCommandType(); InnerCommand execute = context.getInstance(msg); execute.process(msg) ; } // @Test - public void execute8() { + public void execute8() throws Exception { // TODO: 2024/8/31 Integration test String msg = ":pu cross"; InnerCommand execute = context.getInstance(msg); @@ -69,14 +76,14 @@ public void execute8() { } @Test - public void execute9() { + public void execute9() throws Exception { String msg = SystemCommandEnum.INFO.getCommandType(); InnerCommand execute = context.getInstance(msg); execute.process(msg) ; } @Test - public void execute10() { + public void execute10() throws Exception { String msg = "dsds"; InnerCommand execute = context.getInstance(msg); execute.process(msg) ; @@ -85,7 +92,7 @@ public void execute10() { // @Test - public void quit() { + public void quit() throws Exception { String msg = ":q!"; InnerCommand execute = context.getInstance(msg); execute.process(msg) ; diff --git a/cim-client/src/test/java/com/crossoverjie/cim/server/test/CommonTest.java b/cim-client/src/test/java/com/crossoverjie/cim/server/test/CommonTest.java index 25567ade..825fa17d 100644 --- a/cim-client/src/test/java/com/crossoverjie/cim/server/test/CommonTest.java +++ b/cim-client/src/test/java/com/crossoverjie/cim/server/test/CommonTest.java @@ -1,15 +1,20 @@ package com.crossoverjie.cim.server.test; -import com.alibaba.fastjson.JSON; -import com.crossoverjie.cim.client.vo.res.CIMServerResVO; -import com.crossoverjie.cim.client.vo.res.OnlineUsersResVO; +import com.crossoverjie.cim.common.core.proxy.RpcProxyManager; +import com.crossoverjie.cim.common.pojo.CIMUserInfo; +import com.crossoverjie.cim.common.res.BaseResponse; +import com.crossoverjie.cim.route.api.RouteApi; +import com.crossoverjie.cim.route.api.vo.req.LoginReqVO; +import com.crossoverjie.cim.route.api.vo.req.P2PReqVO; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; import com.vdurmont.emoji.EmojiParser; -import lombok.extern.slf4j.Slf4j; -import org.junit.Test; - - import java.io.IOException; +import java.lang.reflect.Method; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.LinkOption; @@ -17,9 +22,12 @@ import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.time.LocalDate; -import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import java.util.Set; +import lombok.extern.slf4j.Slf4j; +import okhttp3.OkHttpClient; +import org.junit.Test; /** * Function: @@ -31,45 +39,7 @@ @Slf4j public class CommonTest { - @Test - public void test() { - String json = "{\"code\":\"9000\",\"message\":\"成功\",\"reqNo\":null,\"dataBody\":{\"ip\":\"127.0.0.1\",\"port\":8081}}" ; - - CIMServerResVO cimServerResVO = JSON.parseObject(json, CIMServerResVO.class); - - System.out.println(cimServerResVO.toString()); - - String text = "nihaoaaa" ; - String[] split = text.split(" "); - System.out.println(split.length); - } - - @Test - public void onlineUser(){ - List onlineUsers = new ArrayList<>(64) ; - - OnlineUsersResVO.DataBodyBean bodyBean = new OnlineUsersResVO.DataBodyBean() ; - - bodyBean.setUserId(100L); - bodyBean.setUserName("zhangsan"); - onlineUsers.add(bodyBean) ; - - bodyBean = new OnlineUsersResVO.DataBodyBean(); - bodyBean.setUserId(200L); - bodyBean.setUserName("crossoverJie"); - onlineUsers.add(bodyBean) ; - - log.info("list={}",JSON.toJSONString(onlineUsers)); - - log.info("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); - - for (OnlineUsersResVO.DataBodyBean onlineUser : onlineUsers) { - - log.info("userId={}=====userName={}",onlineUser.getUserId(),onlineUser.getUserName()); - } - log.info("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); - } @Test @@ -164,4 +134,90 @@ public void emoji2(){ System.out.println("======" + face_with_tears_of_joy.replaceAll("face with tears of joy","\uD83D\uDE02")); } + @Test + public void deSerialize() throws Exception { + RouteApi routeApi = RpcProxyManager.create(RouteApi.class, "http://localhost:8083", new OkHttpClient()); + + BaseResponse login = + routeApi.login(new LoginReqVO(1725722966520L, "cj")); + System.out.println(login.getDataBody()); + + BaseResponse> setBaseResponse = routeApi.onlineUser(); + log.info("setBaseResponse={}",setBaseResponse.getDataBody()); + } + + @Test + public void json() throws JsonProcessingException, ClassNotFoundException { + String json = "{\"code\":\"9000\",\"message\":\"成功\",\"reqNo\":null,\"dataBody\":{\"ip\":\"127.0.0.1\",\"cimServerPort\":11211,\"httpPort\":8081}}"; + + ObjectMapper objectMapper = new ObjectMapper(); + Class generic = null; + for (Method declaredMethod : RouteApi.class.getDeclaredMethods()) { + if (declaredMethod.getName().equals("login")){ + Type returnType = declaredMethod.getGenericReturnType(); + + // check if the return type is a parameterized type + if (returnType instanceof ParameterizedType) { + ParameterizedType parameterizedType = (ParameterizedType) returnType; + + Type[] actualTypeArguments = parameterizedType.getActualTypeArguments(); + + for (Type typeArgument : actualTypeArguments) { + System.out.println("generic: " + typeArgument.getTypeName()); + generic = Class.forName(typeArgument.getTypeName()); + break; + } + } else { + System.out.println("not a generic type"); + } + } + } + BaseResponse response = objectMapper.readValue(json, + objectMapper.getTypeFactory().constructParametricType(BaseResponse.class, generic)); + System.out.println(response.getDataBody().getIp()); + } + + + private static class Gen{ + private T t; + private R r; + } + + interface TestInterface{ + Gen login(); + } + + + @Test + public void test1() throws JsonProcessingException { + String json = "{\"code\":\"200\",\"message\":\"Success\",\"reqNo\":null,\"dataBody\":[{\"userId\":\"123\",\"userName\":\"Alice\"}, {\"userId\":\"456\",\"userName\":\"Bob\"}]}"; + + ObjectMapper objectMapper = new ObjectMapper(); + + // 获取 BaseResponse> 的泛型参数 + Type setType = getGenericTypeOfBaseResponse(); + + // 将泛型类型传递给 ObjectMapper 进行反序列化 + BaseResponse> response = objectMapper.readValue(json, + objectMapper.getTypeFactory().constructParametricType(BaseResponse.class, objectMapper.getTypeFactory().constructType(setType))); + + // 输出结果 + System.out.println("Response Code: " + response.getCode()); + System.out.println("Online Users: "); + for (CIMUserInfo user : response.getDataBody()) { + System.out.println("User ID: " + user.getUserId() + ", User Name: " + user.getUserName()); + } + } + + // 通过反射获取 BaseResponse> 中的泛型类型 + public static Type getGenericTypeOfBaseResponse() { + // 这里模拟你需要处理的 BaseResponse> + ParameterizedType baseResponseType = (ParameterizedType) new TypeReference>>() {}.getType(); + + // 获取 BaseResponse 的泛型参数,即 Set + Type[] actualTypeArguments = baseResponseType.getActualTypeArguments(); + + // 返回第一个泛型参数 (Set) + return actualTypeArguments[0]; + } } diff --git a/cim-client/src/test/java/com/crossoverjie/cim/server/test/RouteTest.java b/cim-client/src/test/java/com/crossoverjie/cim/server/test/RouteTest.java index 0b36ea02..16760c4b 100644 --- a/cim-client/src/test/java/com/crossoverjie/cim/server/test/RouteTest.java +++ b/cim-client/src/test/java/com/crossoverjie/cim/server/test/RouteTest.java @@ -1,16 +1,9 @@ package com.crossoverjie.cim.server.test; -import com.crossoverjie.cim.client.CIMClientApplication; import com.crossoverjie.cim.client.service.RouteRequest; -import com.crossoverjie.cim.client.vo.req.LoginReqVO; -import com.crossoverjie.cim.client.vo.res.CIMServerResVO; +import com.crossoverjie.cim.route.api.vo.req.LoginReqVO; import lombok.extern.slf4j.Slf4j; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; /** * Function: @@ -37,7 +30,7 @@ public class RouteTest { // @Test public void test() throws Exception { LoginReqVO vo = new LoginReqVO(userId,userName) ; - CIMServerResVO.ServerInfo cimServer = routeRequest.getCIMServer(vo); + com.crossoverjie.cim.route.api.vo.res.CIMServerResVO cimServer = routeRequest.getCIMServer(vo); log.info("cimServer=[{}]",cimServer.toString()); } } diff --git a/cim-common/src/main/java/com/crossoverjie/cim/common/core/proxy/ProxyManager.java b/cim-common/src/main/java/com/crossoverjie/cim/common/core/proxy/ProxyManager.java deleted file mode 100644 index ae7101d8..00000000 --- a/cim-common/src/main/java/com/crossoverjie/cim/common/core/proxy/ProxyManager.java +++ /dev/null @@ -1,98 +0,0 @@ -package com.crossoverjie.cim.common.core.proxy; - -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONObject; -import com.crossoverjie.cim.common.exception.CIMException; -import com.crossoverjie.cim.common.util.HttpClient; -import okhttp3.OkHttpClient; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Method; -import java.lang.reflect.Proxy; -import java.net.URI; -import okhttp3.Response; - -import static com.crossoverjie.cim.common.enums.StatusEnum.VALIDATION_FAIL; - -/** - * Function: - * - * @author crossoverJie - * Date: 2020-04-25 00:18 - * @since JDK 1.8 - */ -public final class ProxyManager { - - - private final Class clazz; - - private final String url; - - private final OkHttpClient okHttpClient; - - /** - * @param clazz Proxied interface - * @param url server provider url - * @param okHttpClient http client - */ - public ProxyManager(Class clazz, String url, OkHttpClient okHttpClient) { - this.clazz = clazz; - this.url = url; - this.okHttpClient = okHttpClient; - } - - - /** - * Get proxy instance of api. - * - * @return - */ - public T getInstance() { - return (T) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[]{clazz}, - new ProxyInvocation()); - } - - - private class ProxyInvocation implements InvocationHandler { - - @Override - public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { - - Response result = null; - try { - Request annotation = method.getAnnotation(Request.class); - if (annotation != null && annotation.method().equals(Request.GET)) { - result = HttpClient.get(okHttpClient, url); - } else { - JSONObject jsonObject = new JSONObject(); - String serverUrl = url + "/" + method.getName(); - URI serverUri = new URI(serverUrl); - serverUrl = serverUri.normalize().toString(); - - if (args != null && args.length > 1) { - throw new CIMException(VALIDATION_FAIL); - } - - if (method.getParameterTypes().length > 0) { - Object para = args[0]; - Class parameterType = method.getParameterTypes()[0]; - for (Field field : parameterType.getDeclaredFields()) { - field.setAccessible(true); - jsonObject.put(field.getName(), field.get(para)); - } - } - result = HttpClient.post(okHttpClient, jsonObject.toString(), serverUrl); - } - if (method.getReturnType() == void.class){ - return null; - } - String json = result.body().string(); - return JSON.parseObject(json, method.getReturnType()); - } finally { - if (result != null) { - result.body().close(); - } - } - } - } -} diff --git a/cim-common/src/main/java/com/crossoverjie/cim/common/core/proxy/RpcProxyManager.java b/cim-common/src/main/java/com/crossoverjie/cim/common/core/proxy/RpcProxyManager.java new file mode 100644 index 00000000..f7b728bd --- /dev/null +++ b/cim-common/src/main/java/com/crossoverjie/cim/common/core/proxy/RpcProxyManager.java @@ -0,0 +1,197 @@ +package com.crossoverjie.cim.common.core.proxy; + +import static com.crossoverjie.cim.common.enums.StatusEnum.VALIDATION_FAIL; +import com.alibaba.fastjson.JSONObject; +import com.crossoverjie.cim.common.exception.CIMException; +import com.crossoverjie.cim.common.res.BaseResponse; +import com.crossoverjie.cim.common.util.HttpClient; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Proxy; +import java.lang.reflect.Type; +import java.lang.reflect.TypeVariable; +import java.net.URI; +import lombok.extern.slf4j.Slf4j; +import okhttp3.OkHttpClient; +import okhttp3.Response; + +/** + * RpcProxyManager is a proxy manager for creating dynamic proxy instances of interfaces. + * It handles HTTP requests and responses using OkHttpClient. + * + * @param the type of the proxied interface + */ +@Slf4j +public final class RpcProxyManager { + + private Class clazz; + private String url; + private OkHttpClient okHttpClient; + private final ObjectMapper objectMapper = new ObjectMapper(); + + /** + * Private constructor to initialize RpcProxyManager. + * + * @param clazz Proxied interface + * @param url Server provider URL + * @param okHttpClient HTTP client + */ + private RpcProxyManager(Class clazz, String url, OkHttpClient okHttpClient) { + this.clazz = clazz; + this.url = url; + this.okHttpClient = okHttpClient; + } + + /** + * Default private constructor. + */ + private RpcProxyManager() { + } + + /** + * Creates a proxy instance of the specified interface. + * + * @param clazz Proxied interface + * @param url Server provider URL + * @param okHttpClient HTTP client + * @param Type of the proxied interface + * @return Proxy instance of the specified interface + */ + public static T create(Class clazz, String url, OkHttpClient okHttpClient) { + return new RpcProxyManager<>(clazz, url, okHttpClient).getInstance(); + } + + /** + * Gets the proxy instance of the API. + * + * @return Proxy instance of the API + */ + @SuppressWarnings("unchecked") + public T getInstance() { + return (T) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[]{clazz}, + new ProxyInvocation()); + } + + /** + * ProxyInvocation is an invocation handler for handling method calls on proxy instances. + */ + private class ProxyInvocation implements InvocationHandler { + + /** + * Handles method calls on proxy instances. + * + * @param proxy The proxy instance + * @param method The method being called + * @param args The arguments of the method call + * @return The result of the method call + * @throws Throwable if an error occurs during method invocation + */ + @Override + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + + Response result = null; + String serverUrl = url + "/" + method.getName(); + try { + Request annotation = method.getAnnotation(Request.class); + if (annotation != null && annotation.method().equals(Request.GET)) { + result = HttpClient.get(okHttpClient, serverUrl); + } else { + JSONObject jsonObject = new JSONObject(); + URI serverUri = new URI(serverUrl); + serverUrl = serverUri.normalize().toString(); + + if (args != null && args.length > 1) { + throw new CIMException(VALIDATION_FAIL); + } + + if (method.getParameterTypes().length > 0) { + Object para = args[0]; + Class parameterType = method.getParameterTypes()[0]; + for (Field field : parameterType.getDeclaredFields()) { + field.setAccessible(true); + jsonObject.put(field.getName(), field.get(para)); + } + } + result = HttpClient.post(okHttpClient, jsonObject.toString(), serverUrl); + } + if (method.getReturnType() == void.class) { + return null; + } + + String json = result.body().string(); + Type genericTypeOfBaseResponse = getGenericTypeOfBaseResponse(method); + if (genericTypeOfBaseResponse == null) { + return objectMapper.readValue(json, method.getReturnType()); + } else { + return objectMapper.readValue(json, objectMapper.getTypeFactory() + .constructParametricType(BaseResponse.class, objectMapper.getTypeFactory().constructType(genericTypeOfBaseResponse))); + } + } finally { + if (result != null) { + result.body().close(); + } + } + } + } + + private Type getGenericTypeOfBaseResponse(Method declaredMethod) { + Type returnType = declaredMethod.getGenericReturnType(); + + // check if the return type is a parameterized type + if (returnType instanceof ParameterizedType parameterizedType) { + + Type[] actualTypeArguments = parameterizedType.getActualTypeArguments(); + + for (Type typeArgument : actualTypeArguments) { + return typeArgument; + } + } + + return null; + + } + + /** + * Gets the generic type of the BaseResponse. + * + * @param declaredMethod The method whose return type is being checked + * @return The generic type of the BaseResponse, or null if not found + * @throws ClassNotFoundException if the class of the generic type is not found + */ + private Class getBaseResponseGeneric(Method declaredMethod) throws ClassNotFoundException { + + Type returnType = declaredMethod.getGenericReturnType(); + + // check if the return type is a parameterized type + if (returnType instanceof ParameterizedType parameterizedType) { + + Type[] actualTypeArguments = parameterizedType.getActualTypeArguments(); + + for (Type typeArgument : actualTypeArguments) { + // BaseResponse only has one generic type + return getClass(typeArgument); + } + } + + return null; + } + + public static Class getClass(Type type) throws ClassNotFoundException { + if (type instanceof Class) { + // 普通类型,直接返回 + return (Class) type; + } else if (type instanceof ParameterizedType) { + // 参数化类型,返回原始类型 + return getClass(((ParameterizedType) type).getRawType()); + } else if (type instanceof TypeVariable) { + // 类型变量,无法在运行时获取具体类型 + return Object.class; + } else { + throw new ClassNotFoundException("无法处理的类型: " + type.toString()); + } + } + +} \ No newline at end of file diff --git a/cim-common/src/main/java/com/crossoverjie/cim/common/enums/StatusEnum.java b/cim-common/src/main/java/com/crossoverjie/cim/common/enums/StatusEnum.java index d19afbd7..bff3eaa6 100644 --- a/cim-common/src/main/java/com/crossoverjie/cim/common/enums/StatusEnum.java +++ b/cim-common/src/main/java/com/crossoverjie/cim/common/enums/StatusEnum.java @@ -10,7 +10,7 @@ public enum StatusEnum { /** 成功 */ - SUCCESS("9000", "成功"), + SUCCESS("9000", "Success"), /** 成功 */ FALLBACK("8000", "FALL_BACK"), /** 参数校验失败**/ diff --git a/cim-common/src/main/java/com/crossoverjie/cim/common/pojo/CIMUserInfo.java b/cim-common/src/main/java/com/crossoverjie/cim/common/pojo/CIMUserInfo.java index 2e50f3fa..5c6ed5b7 100644 --- a/cim-common/src/main/java/com/crossoverjie/cim/common/pojo/CIMUserInfo.java +++ b/cim-common/src/main/java/com/crossoverjie/cim/common/pojo/CIMUserInfo.java @@ -1,5 +1,9 @@ package com.crossoverjie.cim.common.pojo; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + /** * Function: 用户信息 * @@ -7,36 +11,11 @@ * Date: 2018/12/24 02:33 * @since JDK 1.8 */ +@Data +@AllArgsConstructor +@NoArgsConstructor public class CIMUserInfo { private Long userId ; private String userName ; - public CIMUserInfo(Long userId, String userName) { - this.userId = userId; - this.userName = userName; - } - - public Long getUserId() { - return userId; - } - - public void setUserId(Long userId) { - this.userId = userId; - } - - public String getUserName() { - return userName; - } - - public void setUserName(String userName) { - this.userName = userName; - } - - @Override - public String toString() { - return "CIMUserInfo{" + - "userId=" + userId + - ", userName='" + userName + '\'' + - '}'; - } } diff --git a/cim-common/src/main/java/com/crossoverjie/cim/common/util/HttpClient.java b/cim-common/src/main/java/com/crossoverjie/cim/common/util/HttpClient.java index 32080a97..a1e4156e 100644 --- a/cim-common/src/main/java/com/crossoverjie/cim/common/util/HttpClient.java +++ b/cim-common/src/main/java/com/crossoverjie/cim/common/util/HttpClient.java @@ -29,7 +29,7 @@ public static Response post(OkHttpClient okHttpClient, String params, String url Response response = okHttpClient.newCall(request).execute(); if (!response.isSuccessful()) { - throw new IOException("Unexpected code " + response); + throw new IOException("RPC failed unexpected code " + response); } return response; diff --git a/cim-common/src/test/java/com/crossoverjie/cim/common/core/proxy/ProxyManagerTest.java b/cim-common/src/test/java/com/crossoverjie/cim/common/core/proxy/RpcProxyManagerTest.java similarity index 59% rename from cim-common/src/test/java/com/crossoverjie/cim/common/core/proxy/ProxyManagerTest.java rename to cim-common/src/test/java/com/crossoverjie/cim/common/core/proxy/RpcProxyManagerTest.java index 2cc401c9..7bcc93c1 100644 --- a/cim-common/src/test/java/com/crossoverjie/cim/common/core/proxy/ProxyManagerTest.java +++ b/cim-common/src/test/java/com/crossoverjie/cim/common/core/proxy/RpcProxyManagerTest.java @@ -1,36 +1,35 @@ package com.crossoverjie.cim.common.core.proxy; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; -import lombok.NoArgsConstructor; import okhttp3.OkHttpClient; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -class ProxyManagerTest { +class RpcProxyManagerTest { @Test public void testGet() { OkHttpClient client = new OkHttpClient(); - Github github = - new ProxyManager<>(Github.class, "https://api.github.com/users/crossoverjie", - client) - .getInstance(); - GithubResponse githubResponse = github.userInfo(); + String url = "https://api.github.com/users"; + Github github = RpcProxyManager.create(Github.class, url, client); + GithubResponse githubResponse = github.crossoverjie(); Assertions.assertEquals(githubResponse.getName(), "crossoverJie"); - github.userInfo2(); + github.torvalds(); } interface Github { @Request(method = Request.GET) - GithubResponse userInfo(); + GithubResponse crossoverjie(); + @Request(method = Request.GET) - void userInfo2(); + void torvalds(); } - @NoArgsConstructor @Data + @JsonIgnoreProperties(ignoreUnknown = true) public static class GithubResponse { @JsonProperty("name") private String name; diff --git a/cim-forward-route/src/main/java/com/crossoverjie/cim/route/controller/RouteController.java b/cim-forward-route/src/main/java/com/crossoverjie/cim/route/controller/RouteController.java index a9959f67..bdcaa8e0 100644 --- a/cim-forward-route/src/main/java/com/crossoverjie/cim/route/controller/RouteController.java +++ b/cim-forward-route/src/main/java/com/crossoverjie/cim/route/controller/RouteController.java @@ -168,7 +168,7 @@ public BaseResponse login(@RequestBody LoginReqVO loginReqVO) th //保存路由信息 accountService.saveRouteInfo(loginReqVO,server); - CIMServerResVO vo = new CIMServerResVO(routeInfo); + CIMServerResVO vo = new CIMServerResVO(routeInfo.getIp(), routeInfo.getCimServerPort(), routeInfo.getHttpPort()); res.setDataBody(vo); } @@ -206,7 +206,7 @@ public BaseResponse registerAccount(@RequestBody RegisterInfo * @return */ @Operation(summary = "获取所有在线用户") - @RequestMapping(value = "onlineUser", method = RequestMethod.POST) + @RequestMapping(value = "onlineUser", method = RequestMethod.GET) @ResponseBody() @Override public BaseResponse> onlineUser() throws Exception { diff --git a/cim-forward-route/src/main/java/com/crossoverjie/cim/route/service/impl/AccountServiceRedisImpl.java b/cim-forward-route/src/main/java/com/crossoverjie/cim/route/service/impl/AccountServiceRedisImpl.java index ac23d2fb..e05299a6 100644 --- a/cim-forward-route/src/main/java/com/crossoverjie/cim/route/service/impl/AccountServiceRedisImpl.java +++ b/cim-forward-route/src/main/java/com/crossoverjie/cim/route/service/impl/AccountServiceRedisImpl.java @@ -1,9 +1,10 @@ package com.crossoverjie.cim.route.service.impl; -import com.crossoverjie.cim.common.core.proxy.ProxyManager; +import com.crossoverjie.cim.common.core.proxy.RpcProxyManager; import com.crossoverjie.cim.common.enums.StatusEnum; import com.crossoverjie.cim.common.exception.CIMException; import com.crossoverjie.cim.common.pojo.CIMUserInfo; +import com.crossoverjie.cim.common.pojo.RouteInfo; import com.crossoverjie.cim.common.util.RouteInfoParseUtil; import com.crossoverjie.cim.route.api.vo.req.ChatReqVO; import com.crossoverjie.cim.route.api.vo.req.LoginReqVO; @@ -130,14 +131,16 @@ public CIMServerResVO loadRouteRelatedByUserId(Long userId) { throw new CIMException(OFF_LINE); } - CIMServerResVO cimServerResVO = new CIMServerResVO(RouteInfoParseUtil.parse(value)); + RouteInfo parse = RouteInfoParseUtil.parse(value); + CIMServerResVO cimServerResVO = new CIMServerResVO(parse.getIp(), parse.getCimServerPort(), parse.getHttpPort()); return cimServerResVO; } private void parseServerInfo(Map routes, String key) { long userId = Long.valueOf(key.split(":")[1]); String value = redisTemplate.opsForValue().get(key); - CIMServerResVO cimServerResVO = new CIMServerResVO(RouteInfoParseUtil.parse(value)); + RouteInfo parse = RouteInfoParseUtil.parse(value); + CIMServerResVO cimServerResVO = new CIMServerResVO(parse.getIp(), parse.getCimServerPort(), parse.getHttpPort()); routes.put(userId, cimServerResVO); } @@ -147,16 +150,9 @@ public void pushMsg(CIMServerResVO cimServerResVO, long sendUserId, ChatReqVO gr CIMUserInfo cimUserInfo = userInfoCacheService.loadUserInfoByUserId(sendUserId); String url = "http://" + cimServerResVO.getIp() + ":" + cimServerResVO.getHttpPort(); - ServerApi serverApi = new ProxyManager<>(ServerApi.class, url, okHttpClient).getInstance(); + ServerApi serverApi = RpcProxyManager.create(ServerApi.class, url, okHttpClient); SendMsgReqVO vo = new SendMsgReqVO(cimUserInfo.getUserName() + ":" + groupReqVO.getMsg(), groupReqVO.getUserId()); - Response response = null; - try { - response = (Response) serverApi.sendMsg(vo); - } catch (Exception e) { - log.error("Exception", e); - } finally { - response.body().close(); - } + serverApi.sendMsg(vo); } @Override diff --git a/cim-integration-test/src/test/java/com/crossoverjie/cim/client/ClientTest.java b/cim-integration-test/src/test/java/com/crossoverjie/cim/client/ClientTest.java index a916598f..6b183fb0 100644 --- a/cim-integration-test/src/test/java/com/crossoverjie/cim/client/ClientTest.java +++ b/cim-integration-test/src/test/java/com/crossoverjie/cim/client/ClientTest.java @@ -2,7 +2,9 @@ import com.crossoverjie.cim.client.service.MsgHandle; import com.crossoverjie.cim.client.util.SpringBeanFactory; +import com.crossoverjie.cim.common.pojo.CIMUserInfo; import com.crossoverjie.cim.route.AbstractRouteBaseTest; +import java.util.concurrent.TimeUnit; import lombok.extern.slf4j.Slf4j; import org.junit.Test; import org.springframework.boot.SpringApplication; @@ -32,6 +34,7 @@ public void olu() throws Exception { MsgHandle msgHandle = SpringBeanFactory.getBean(MsgHandle.class); msgHandle.innerCommand(":olu"); msgHandle.sendMsg("hello"); + TimeUnit.SECONDS.sleep(1); } diff --git a/cim-rout-api/src/main/java/com/crossoverjie/cim/route/api/RouteApi.java b/cim-rout-api/src/main/java/com/crossoverjie/cim/route/api/RouteApi.java index cc1ec85f..665e2276 100644 --- a/cim-rout-api/src/main/java/com/crossoverjie/cim/route/api/RouteApi.java +++ b/cim-rout-api/src/main/java/com/crossoverjie/cim/route/api/RouteApi.java @@ -1,12 +1,16 @@ package com.crossoverjie.cim.route.api; import com.crossoverjie.cim.common.core.proxy.Request; +import com.crossoverjie.cim.common.pojo.CIMUserInfo; import com.crossoverjie.cim.common.res.BaseResponse; +import com.crossoverjie.cim.common.res.NULLBody; import com.crossoverjie.cim.route.api.vo.req.ChatReqVO; import com.crossoverjie.cim.route.api.vo.req.LoginReqVO; import com.crossoverjie.cim.route.api.vo.req.P2PReqVO; import com.crossoverjie.cim.route.api.vo.req.RegisterInfoReqVO; +import com.crossoverjie.cim.route.api.vo.res.CIMServerResVO; import com.crossoverjie.cim.route.api.vo.res.RegisterInfoResVO; +import java.util.Set; /** * Function: Route Api @@ -24,7 +28,7 @@ public interface RouteApi { * @return * @throws Exception */ - Object groupRoute(ChatReqVO groupReqVO) throws Exception; + BaseResponse groupRoute(ChatReqVO groupReqVO) throws Exception; /** * Point to point chat @@ -32,7 +36,7 @@ public interface RouteApi { * @return * @throws Exception */ - Object p2pRoute(P2PReqVO p2pRequest) throws Exception; + BaseResponse p2pRoute(P2PReqVO p2pRequest) throws Exception; /** @@ -42,7 +46,7 @@ public interface RouteApi { * @return * @throws Exception */ - Object offLine(ChatReqVO groupReqVO) throws Exception; + BaseResponse offLine(ChatReqVO groupReqVO) throws Exception; /** * Login account @@ -50,7 +54,7 @@ public interface RouteApi { * @return * @throws Exception */ - Object login(LoginReqVO loginReqVO) throws Exception; + BaseResponse login(LoginReqVO loginReqVO) throws Exception; /** * Register account @@ -68,7 +72,7 @@ public interface RouteApi { * @throws Exception */ @Request(method = Request.GET) - Object onlineUser() throws Exception; + BaseResponse> onlineUser() throws Exception; // TODO: 2024/8/19 Get cache server & metastore server } diff --git a/cim-rout-api/src/main/java/com/crossoverjie/cim/route/api/vo/req/ChatReqVO.java b/cim-rout-api/src/main/java/com/crossoverjie/cim/route/api/vo/req/ChatReqVO.java index 10c6a682..53b2a01b 100644 --- a/cim-rout-api/src/main/java/com/crossoverjie/cim/route/api/vo/req/ChatReqVO.java +++ b/cim-rout-api/src/main/java/com/crossoverjie/cim/route/api/vo/req/ChatReqVO.java @@ -4,6 +4,10 @@ import io.swagger.v3.oas.annotations.media.Schema; import jakarta.validation.constraints.NotNull; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.NoArgsConstructor; /** * Function: Google Protocol 编解码发送 @@ -12,6 +16,10 @@ * Date: 2018/05/21 15:56 * @since JDK 1.8 */ +@EqualsAndHashCode(callSuper = true) +@Data +@AllArgsConstructor +@NoArgsConstructor public class ChatReqVO extends BaseRequest { @NotNull(message = "userId 不能为空") @@ -23,29 +31,6 @@ public class ChatReqVO extends BaseRequest { @Schema(requiredMode = Schema.RequiredMode.REQUIRED, description = "msg", example = "hello") private String msg ; - public ChatReqVO() { - } - - public ChatReqVO(Long userId, String msg) { - this.userId = userId; - this.msg = msg; - } - - public String getMsg() { - return msg; - } - - public void setMsg(String msg) { - this.msg = msg; - } - - public Long getUserId() { - return userId; - } - - public void setUserId(Long userId) { - this.userId = userId; - } @Override public String toString() { diff --git a/cim-rout-api/src/main/java/com/crossoverjie/cim/route/api/vo/req/LoginReqVO.java b/cim-rout-api/src/main/java/com/crossoverjie/cim/route/api/vo/req/LoginReqVO.java index fcd97d8f..8e810d80 100644 --- a/cim-rout-api/src/main/java/com/crossoverjie/cim/route/api/vo/req/LoginReqVO.java +++ b/cim-rout-api/src/main/java/com/crossoverjie/cim/route/api/vo/req/LoginReqVO.java @@ -1,6 +1,7 @@ package com.crossoverjie.cim.route.api.vo.req; import com.crossoverjie.cim.common.req.BaseRequest; +import lombok.AllArgsConstructor; /** * Function: @@ -9,6 +10,7 @@ * Date: 2018/12/23 22:30 * @since JDK 1.8 */ +@AllArgsConstructor public class LoginReqVO extends BaseRequest{ private Long userId ; private String userName ; diff --git a/cim-rout-api/src/main/java/com/crossoverjie/cim/route/api/vo/res/CIMServerResVO.java b/cim-rout-api/src/main/java/com/crossoverjie/cim/route/api/vo/res/CIMServerResVO.java index cec52bfb..07911f84 100644 --- a/cim-rout-api/src/main/java/com/crossoverjie/cim/route/api/vo/res/CIMServerResVO.java +++ b/cim-rout-api/src/main/java/com/crossoverjie/cim/route/api/vo/res/CIMServerResVO.java @@ -3,6 +3,9 @@ import com.crossoverjie.cim.common.pojo.RouteInfo; import java.io.Serializable; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; /** * Function: @@ -11,39 +14,13 @@ * Date: 2018/12/23 00:43 * @since JDK 1.8 */ +@Data +@AllArgsConstructor +@NoArgsConstructor public class CIMServerResVO implements Serializable { private String ip ; private Integer cimServerPort; private Integer httpPort; - public CIMServerResVO(RouteInfo routeInfo) { - this.ip = routeInfo.getIp(); - this.cimServerPort = routeInfo.getCimServerPort(); - this.httpPort = routeInfo.getHttpPort(); - } - - public String getIp() { - return ip; - } - - public void setIp(String ip) { - this.ip = ip; - } - - public Integer getCimServerPort() { - return cimServerPort; - } - - public void setCimServerPort(Integer cimServerPort) { - this.cimServerPort = cimServerPort; - } - - public Integer getHttpPort() { - return httpPort; - } - - public void setHttpPort(Integer httpPort) { - this.httpPort = httpPort; - } } diff --git a/cim-server-api/src/main/java/com/crossoverjie/cim/server/api/ServerApi.java b/cim-server-api/src/main/java/com/crossoverjie/cim/server/api/ServerApi.java index 9e1be26e..b36d3857 100644 --- a/cim-server-api/src/main/java/com/crossoverjie/cim/server/api/ServerApi.java +++ b/cim-server-api/src/main/java/com/crossoverjie/cim/server/api/ServerApi.java @@ -1,6 +1,8 @@ package com.crossoverjie.cim.server.api; +import com.crossoverjie.cim.common.res.BaseResponse; import com.crossoverjie.cim.server.api.vo.req.SendMsgReqVO; +import com.crossoverjie.cim.server.api.vo.res.SendMsgResVO; /** * Function: @@ -17,5 +19,5 @@ public interface ServerApi { * @return * @throws Exception */ - Object sendMsg(SendMsgReqVO sendMsgReqVO) throws Exception; + BaseResponse sendMsg(SendMsgReqVO sendMsgReqVO) throws Exception; } diff --git a/cim-server/src/main/java/com/crossoverjie/cim/server/kit/RouteHandler.java b/cim-server/src/main/java/com/crossoverjie/cim/server/kit/RouteHandler.java index a70aadb9..c959293a 100644 --- a/cim-server/src/main/java/com/crossoverjie/cim/server/kit/RouteHandler.java +++ b/cim-server/src/main/java/com/crossoverjie/cim/server/kit/RouteHandler.java @@ -1,6 +1,6 @@ package com.crossoverjie.cim.server.kit; -import com.crossoverjie.cim.common.core.proxy.ProxyManager; +import com.crossoverjie.cim.common.core.proxy.RpcProxyManager; import com.crossoverjie.cim.common.pojo.CIMUserInfo; import com.crossoverjie.cim.route.api.RouteApi; import com.crossoverjie.cim.route.api.vo.req.ChatReqVO; @@ -58,15 +58,12 @@ public void userOffLine(CIMUserInfo userInfo, NioSocketChannel channel) throws I * @throws IOException */ public void clearRouteInfo(CIMUserInfo userInfo) { - RouteApi routeApi = new ProxyManager<>(RouteApi.class, configuration.getRouteUrl(), okHttpClient).getInstance(); - Response response = null; + RouteApi routeApi = RpcProxyManager.create(RouteApi.class, configuration.getRouteUrl(), okHttpClient); ChatReqVO vo = new ChatReqVO(userInfo.getUserId(), userInfo.getUserName()); try { - response = (Response) routeApi.offLine(vo); + routeApi.offLine(vo); } catch (Exception e){ log.error("Exception",e); - }finally { - response.body().close(); } } From 7c499aeb83a840b5967067098c8836668c4aa310 Mon Sep 17 00:00:00 2001 From: crossoverJie Date: Sun, 8 Sep 2024 00:04:46 +0800 Subject: [PATCH 3/8] remove test --- .../test/java/com/crossoverjie/cim/server/test/CommonTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cim-client/src/test/java/com/crossoverjie/cim/server/test/CommonTest.java b/cim-client/src/test/java/com/crossoverjie/cim/server/test/CommonTest.java index 825fa17d..cb9d7f1f 100644 --- a/cim-client/src/test/java/com/crossoverjie/cim/server/test/CommonTest.java +++ b/cim-client/src/test/java/com/crossoverjie/cim/server/test/CommonTest.java @@ -134,7 +134,7 @@ public void emoji2(){ System.out.println("======" + face_with_tears_of_joy.replaceAll("face with tears of joy","\uD83D\uDE02")); } - @Test +// @Test public void deSerialize() throws Exception { RouteApi routeApi = RpcProxyManager.create(RouteApi.class, "http://localhost:8083", new OkHttpClient()); From a166bc5c4a306e645d6cbd6b463363c1eace6372 Mon Sep 17 00:00:00 2001 From: crossoverJie Date: Sun, 8 Sep 2024 20:08:18 +0800 Subject: [PATCH 4/8] add Rpc proxy test --- .../cim/common/core/proxy/Request.java | 1 + .../common/core/proxy/RpcProxyManager.java | 8 +- .../core/proxy/RpcProxyManagerTest.java | 86 ++++++++++++++++++- 3 files changed, 92 insertions(+), 3 deletions(-) diff --git a/cim-common/src/main/java/com/crossoverjie/cim/common/core/proxy/Request.java b/cim-common/src/main/java/com/crossoverjie/cim/common/core/proxy/Request.java index 778a5b5c..e5d797e8 100644 --- a/cim-common/src/main/java/com/crossoverjie/cim/common/core/proxy/Request.java +++ b/cim-common/src/main/java/com/crossoverjie/cim/common/core/proxy/Request.java @@ -9,6 +9,7 @@ @Retention(RetentionPolicy.RUNTIME) public @interface Request { String method() default POST; + String url() default ""; String GET = "GET"; String POST = "POST"; diff --git a/cim-common/src/main/java/com/crossoverjie/cim/common/core/proxy/RpcProxyManager.java b/cim-common/src/main/java/com/crossoverjie/cim/common/core/proxy/RpcProxyManager.java index f7b728bd..fc6e8653 100644 --- a/cim-common/src/main/java/com/crossoverjie/cim/common/core/proxy/RpcProxyManager.java +++ b/cim-common/src/main/java/com/crossoverjie/cim/common/core/proxy/RpcProxyManager.java @@ -5,6 +5,7 @@ import com.crossoverjie.cim.common.exception.CIMException; import com.crossoverjie.cim.common.res.BaseResponse; import com.crossoverjie.cim.common.util.HttpClient; +import com.crossoverjie.cim.common.util.StringUtil; import com.fasterxml.jackson.databind.ObjectMapper; import java.lang.reflect.Field; import java.lang.reflect.InvocationHandler; @@ -94,9 +95,12 @@ public Object invoke(Object proxy, Method method, Object[] args) throws Throwabl Response result = null; String serverUrl = url + "/" + method.getName(); + Request annotation = method.getAnnotation(Request.class); + if (StringUtil.isNotEmpty(annotation.url())) { + serverUrl = url + "/" + annotation.url(); + } try { - Request annotation = method.getAnnotation(Request.class); - if (annotation != null && annotation.method().equals(Request.GET)) { + if (annotation.method().equals(Request.GET)) { result = HttpClient.get(okHttpClient, serverUrl); } else { JSONObject jsonObject = new JSONObject(); diff --git a/cim-common/src/test/java/com/crossoverjie/cim/common/core/proxy/RpcProxyManagerTest.java b/cim-common/src/test/java/com/crossoverjie/cim/common/core/proxy/RpcProxyManagerTest.java index 7bcc93c1..4ed24965 100644 --- a/cim-common/src/test/java/com/crossoverjie/cim/common/core/proxy/RpcProxyManagerTest.java +++ b/cim-common/src/test/java/com/crossoverjie/cim/common/core/proxy/RpcProxyManagerTest.java @@ -3,6 +3,7 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; +import lombok.NoArgsConstructor; import okhttp3.OkHttpClient; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; @@ -16,10 +17,93 @@ public void testGet() { Github github = RpcProxyManager.create(Github.class, url, client); GithubResponse githubResponse = github.crossoverjie(); Assertions.assertEquals(githubResponse.getName(), "crossoverJie"); - github.torvalds(); } + @Test + public void testPost() { + OkHttpClient client = new OkHttpClient(); + String url = "http://echo.free.beeceptor.com"; + Echo echo = RpcProxyManager.create(Echo.class, url, client); + EchoRequest request = new EchoRequest(); + request.setName("crossoverJie"); + request.setAge(18); + request.setCity("shenzhen"); + EchoResponse response = echo.echo(request); + Assertions.assertEquals(response.getParsedBody().getName(), "crossoverJie"); + Assertions.assertEquals(response.getParsedBody().getAge(), 18); + Assertions.assertEquals(response.getParsedBody().getCity(), "shenzhen"); + } + + interface Echo { + @Request(url = "sample-request?author=beeceptor") + EchoResponse echo(EchoRequest message); + } + + @Data + public static class EchoRequest{ + private String name; + private int age; + private String city; + } + + @NoArgsConstructor + @Data + public static class EchoResponse{ + + @JsonProperty("method") + private String method; + @JsonProperty("protocol") + private String protocol; + @JsonProperty("host") + private String host; + @JsonProperty("path") + private String path; + @JsonProperty("ip") + private String ip; + @JsonProperty("headers") + private HeadersDTO headers; + @JsonProperty("parsedQueryParams") + private ParsedQueryParamsDTO parsedQueryParams; + @JsonProperty("parsedBody") + private ParsedBodyDTO parsedBody; + + @NoArgsConstructor + @Data + public static class HeadersDTO { + @JsonProperty("Host") + private String host; + @JsonProperty("User-Agent") + private String userAgent; + @JsonProperty("Content-Length") + private String contentLength; + @JsonProperty("Accept") + private String accept; + @JsonProperty("Content-Type") + private String contentType; + @JsonProperty("Accept-Encoding") + private String acceptEncoding; + } + + @NoArgsConstructor + @Data + public static class ParsedQueryParamsDTO { + @JsonProperty("author") + private String author; + } + + @NoArgsConstructor + @Data + public static class ParsedBodyDTO { + @JsonProperty("name") + private String name; + @JsonProperty("age") + private Integer age; + @JsonProperty("city") + private String city; + } + } + interface Github { @Request(method = Request.GET) GithubResponse crossoverjie(); From 2d6f9017fd82a35a94384d208acc3c3aa50054f8 Mon Sep 17 00:00:00 2001 From: crossoverJie Date: Sun, 8 Sep 2024 20:10:23 +0800 Subject: [PATCH 5/8] add Rpc proxy test --- .../crossoverjie/cim/common/core/proxy/RpcProxyManager.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cim-common/src/main/java/com/crossoverjie/cim/common/core/proxy/RpcProxyManager.java b/cim-common/src/main/java/com/crossoverjie/cim/common/core/proxy/RpcProxyManager.java index fc6e8653..6176de62 100644 --- a/cim-common/src/main/java/com/crossoverjie/cim/common/core/proxy/RpcProxyManager.java +++ b/cim-common/src/main/java/com/crossoverjie/cim/common/core/proxy/RpcProxyManager.java @@ -96,11 +96,11 @@ public Object invoke(Object proxy, Method method, Object[] args) throws Throwabl Response result = null; String serverUrl = url + "/" + method.getName(); Request annotation = method.getAnnotation(Request.class); - if (StringUtil.isNotEmpty(annotation.url())) { + if (annotation != null && StringUtil.isNotEmpty(annotation.url())) { serverUrl = url + "/" + annotation.url(); } try { - if (annotation.method().equals(Request.GET)) { + if (annotation != null && annotation.method().equals(Request.GET)) { result = HttpClient.get(okHttpClient, serverUrl); } else { JSONObject jsonObject = new JSONObject(); From 88bdea922d20f1533f681d13899f4efc5add2368 Mon Sep 17 00:00:00 2001 From: crossoverJie Date: Sun, 8 Sep 2024 20:14:28 +0800 Subject: [PATCH 6/8] comment unless code --- .../test/java/com/crossoverjie/cim/server/test/CommonTest.java | 1 - .../crossoverjie/cim/common/core/proxy/RpcProxyManager.java | 3 +-- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/cim-client/src/test/java/com/crossoverjie/cim/server/test/CommonTest.java b/cim-client/src/test/java/com/crossoverjie/cim/server/test/CommonTest.java index cb9d7f1f..7233389b 100644 --- a/cim-client/src/test/java/com/crossoverjie/cim/server/test/CommonTest.java +++ b/cim-client/src/test/java/com/crossoverjie/cim/server/test/CommonTest.java @@ -201,7 +201,6 @@ public void test1() throws JsonProcessingException { BaseResponse> response = objectMapper.readValue(json, objectMapper.getTypeFactory().constructParametricType(BaseResponse.class, objectMapper.getTypeFactory().constructType(setType))); - // 输出结果 System.out.println("Response Code: " + response.getCode()); System.out.println("Online Users: "); for (CIMUserInfo user : response.getDataBody()) { diff --git a/cim-common/src/main/java/com/crossoverjie/cim/common/core/proxy/RpcProxyManager.java b/cim-common/src/main/java/com/crossoverjie/cim/common/core/proxy/RpcProxyManager.java index 6176de62..13d82207 100644 --- a/cim-common/src/main/java/com/crossoverjie/cim/common/core/proxy/RpcProxyManager.java +++ b/cim-common/src/main/java/com/crossoverjie/cim/common/core/proxy/RpcProxyManager.java @@ -164,7 +164,6 @@ private Type getGenericTypeOfBaseResponse(Method declaredMethod) { * @param declaredMethod The method whose return type is being checked * @return The generic type of the BaseResponse, or null if not found * @throws ClassNotFoundException if the class of the generic type is not found - */ private Class getBaseResponseGeneric(Method declaredMethod) throws ClassNotFoundException { Type returnType = declaredMethod.getGenericReturnType(); @@ -196,6 +195,6 @@ public static Class getClass(Type type) throws ClassNotFoundException { } else { throw new ClassNotFoundException("无法处理的类型: " + type.toString()); } - } + }*/ } \ No newline at end of file From 2dffa42aa4e2fe03e4efecf0df2f4f176ce6c31c Mon Sep 17 00:00:00 2001 From: crossoverJie Date: Sun, 8 Sep 2024 21:08:17 +0800 Subject: [PATCH 7/8] comment unless code --- .../common/core/proxy/RpcProxyManager.java | 4 +- .../core/proxy/RpcProxyManagerTest.java | 59 +++++++++++++++++++ 2 files changed, 61 insertions(+), 2 deletions(-) diff --git a/cim-common/src/main/java/com/crossoverjie/cim/common/core/proxy/RpcProxyManager.java b/cim-common/src/main/java/com/crossoverjie/cim/common/core/proxy/RpcProxyManager.java index 13d82207..c9406ef7 100644 --- a/cim-common/src/main/java/com/crossoverjie/cim/common/core/proxy/RpcProxyManager.java +++ b/cim-common/src/main/java/com/crossoverjie/cim/common/core/proxy/RpcProxyManager.java @@ -108,7 +108,7 @@ public Object invoke(Object proxy, Method method, Object[] args) throws Throwabl serverUrl = serverUri.normalize().toString(); if (args != null && args.length > 1) { - throw new CIMException(VALIDATION_FAIL); + throw new IllegalArgumentException(VALIDATION_FAIL.message()); } if (method.getParameterTypes().length > 0) { @@ -131,7 +131,7 @@ public Object invoke(Object proxy, Method method, Object[] args) throws Throwabl return objectMapper.readValue(json, method.getReturnType()); } else { return objectMapper.readValue(json, objectMapper.getTypeFactory() - .constructParametricType(BaseResponse.class, objectMapper.getTypeFactory().constructType(genericTypeOfBaseResponse))); + .constructParametricType(method.getReturnType(), objectMapper.getTypeFactory().constructType(genericTypeOfBaseResponse))); } } finally { if (result != null) { diff --git a/cim-common/src/test/java/com/crossoverjie/cim/common/core/proxy/RpcProxyManagerTest.java b/cim-common/src/test/java/com/crossoverjie/cim/common/core/proxy/RpcProxyManagerTest.java index 4ed24965..8a7718a2 100644 --- a/cim-common/src/test/java/com/crossoverjie/cim/common/core/proxy/RpcProxyManagerTest.java +++ b/cim-common/src/test/java/com/crossoverjie/cim/common/core/proxy/RpcProxyManagerTest.java @@ -2,12 +2,17 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; +import java.io.Serializable; +import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import okhttp3.OkHttpClient; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.junit.jupiter.MockitoExtension; +@ExtendWith(MockitoExtension.class) class RpcProxyManagerTest { @Test @@ -35,9 +40,40 @@ public void testPost() { Assertions.assertEquals(response.getParsedBody().getCity(), "shenzhen"); } + @Test + public void testFail() { + OkHttpClient client = new OkHttpClient(); + String url = "http://echo.free.beeceptor.com"; + Echo echo = RpcProxyManager.create(Echo.class, url, client); + EchoRequest request = new EchoRequest(); + request.setName("crossoverJie"); + request.setAge(18); + request.setCity("shenzhen"); + Assertions.assertThrows(IllegalArgumentException.class, () -> echo.fail(request, "test")); + } + + + @Test + public void testGeneric() { + OkHttpClient client = new OkHttpClient(); + String url = "http://echo.free.beeceptor.com"; + Echo echo = RpcProxyManager.create(Echo.class, url, client); + EchoRequest request = new EchoRequest(); + request.setName("crossoverJie"); + request.setAge(18); + request.setCity("shenzhen"); + EchoGeneric response = echo.echoGeneric(request); + Assertions.assertEquals(response.getHeaders().getHost(), "echo.free.beeceptor.com"); + } + interface Echo { @Request(url = "sample-request?author=beeceptor") EchoResponse echo(EchoRequest message); + @Request(url = "sample-request?author=beeceptor") + EchoResponse fail(EchoRequest message, String s); + + @Request(url = "sample-request?author=beeceptor") + EchoGeneric echoGeneric(EchoRequest message); } @Data @@ -47,6 +83,29 @@ public static class EchoRequest{ private String city; } + @Data + @AllArgsConstructor + @NoArgsConstructor + public static class CIMServerResVO implements Serializable { + + private String ip ; + private Integer cimServerPort; + private Integer httpPort; + + } + + @Data + @JsonIgnoreProperties(ignoreUnknown = true) + @AllArgsConstructor + @NoArgsConstructor + public static class EchoGeneric { + private String method; + private String protocol; + private String host; + + private T headers; + } + @NoArgsConstructor @Data public static class EchoResponse{ From e951ade824a9064056079e0b6be3dfb9f10f9c4f Mon Sep 17 00:00:00 2001 From: crossoverJie Date: Sun, 8 Sep 2024 21:09:24 +0800 Subject: [PATCH 8/8] comment unless code --- .../crossoverjie/cim/common/core/proxy/RpcProxyManagerTest.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/cim-common/src/test/java/com/crossoverjie/cim/common/core/proxy/RpcProxyManagerTest.java b/cim-common/src/test/java/com/crossoverjie/cim/common/core/proxy/RpcProxyManagerTest.java index 8a7718a2..834b90e5 100644 --- a/cim-common/src/test/java/com/crossoverjie/cim/common/core/proxy/RpcProxyManagerTest.java +++ b/cim-common/src/test/java/com/crossoverjie/cim/common/core/proxy/RpcProxyManagerTest.java @@ -10,9 +10,7 @@ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.junit.jupiter.MockitoExtension; -@ExtendWith(MockitoExtension.class) class RpcProxyManagerTest { @Test