Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/feature rpc 20200424 #93

Merged
merged 7 commits into from
Apr 25, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ nohup java -jar /root/work/route0/cim-forward-route-1.0.0-SNAPSHOT.jar --app.zk
```shell
cp /cim/cim-client/target/cim-client-1.0.0-SNAPSHOT.jar /xx/work/route0/
cd /xx/work/route0/
java -jar cim-client-1.0.0-SNAPSHOT.jar --server.port=8084 --cim.user.id=唯一客户端ID --cim.user.userName=用户名 --cim.group.route.request.url=http://路由服务器:8083/groupRoute --cim.server.route.request.url=http://路由服务器:8083/login
java -jar cim-client-1.0.0-SNAPSHOT.jar --server.port=8084 --cim.user.id=唯一客户端ID --cim.user.userName=用户名 --cim.route.url=http://路由服务器:8083/
```

![](https://ws2.sinaimg.cn/large/006tNbRwly1fylgxjgshfj31vo04m7p9.jpg)
Expand Down Expand Up @@ -167,7 +167,7 @@ curl -X POST --header 'Content-Type: application/json' --header 'Accept: applica
# 启动本地客户端
cp /cim/cim-client/target/cim-client-1.0.0-SNAPSHOT.jar /xx/work/route0/
cd /xx/work/route0/
java -jar cim-client-1.0.0-SNAPSHOT.jar --server.port=8084 --cim.user.id=上方返回的userId --cim.user.userName=用户名 --cim.group.route.request.url=http://路由服务器:8083/groupRoute --cim.server.route.request.url=http://路由服务器:8083/login
java -jar cim-client-1.0.0-SNAPSHOT.jar --server.port=8084 --cim.user.id=上方返回的userId --cim.user.userName=用户名 --cim.route.url=http://路由服务器:8083/
```

## 客户端内置命令
Expand Down
5 changes: 5 additions & 0 deletions cim-client/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,11 @@
<version>5.0.0</version>
</dependency>

<dependency>
<groupId>com.crossoverjie.netty</groupId>
<artifactId>cim-rout-api</artifactId>
</dependency>

</dependencies>

<build>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package com.crossoverjie.cim.client.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.crossoverjie.cim.client.config.AppConfiguration;
import com.crossoverjie.cim.client.service.EchoService;
import com.crossoverjie.cim.client.service.RouteRequest;
Expand All @@ -11,17 +10,20 @@
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.enums.StatusEnum;
import com.crossoverjie.cim.common.exception.CIMException;
import com.crossoverjie.cim.common.res.BaseResponse;
import okhttp3.*;
import com.crossoverjie.cim.route.api.RouteApi;
import com.crossoverjie.cim.route.api.vo.req.ChatReqVO;
import okhttp3.OkHttpClient;
import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

/**
Expand All @@ -39,19 +41,8 @@ public class RouteRequestImpl implements RouteRequest {
@Autowired
private OkHttpClient okHttpClient ;

private MediaType mediaType = MediaType.parse("application/json");

@Value("${cim.group.route.request.url}")
private String groupRouteRequestUrl;

@Value("${cim.p2p.route.request.url}")
private String p2pRouteRequestUrl;

@Value("${cim.server.route.request.url}")
private String serverRouteLoginUrl;

@Value("${cim.server.online.user.url}")
private String onlineUserUrl;
@Value("${cim.route.url}")
private String routeUrl ;

@Autowired
private EchoService echoService ;
Expand All @@ -62,81 +53,57 @@ public class RouteRequestImpl implements RouteRequest {

@Override
public void sendGroupMsg(GroupReqVO groupReqVO) throws Exception {

JSONObject jsonObject = new JSONObject();
jsonObject.put("msg",groupReqVO.getMsg());
jsonObject.put("userId",groupReqVO.getUserId());
RequestBody requestBody = RequestBody.create(mediaType,jsonObject.toString());

Request request = new Request.Builder()
.url(groupRouteRequestUrl)
.post(requestBody)
.build();

Response response = okHttpClient.newCall(request).execute() ;
RouteApi routeApi = new ProxyManager<>(RouteApi.class, routeUrl, okHttpClient).getInstance();
ChatReqVO chatReqVO = new ChatReqVO(groupReqVO.getUserId(), groupReqVO.getMsg()) ;
Response response = null;
try {
if (!response.isSuccessful()){
throw new IOException("Unexpected code " + response);
}
response = (Response)routeApi.groupRoute(chatReqVO);
}catch (Exception e){
LOGGER.error("exception",e);
}finally {
response.body().close();
}
}

@Override
public void sendP2PMsg(P2PReqVO p2PReqVO) throws Exception {
JSONObject jsonObject = new JSONObject();
jsonObject.put("msg",p2PReqVO.getMsg());
jsonObject.put("userId",p2PReqVO.getUserId());
jsonObject.put("receiveUserId",p2PReqVO.getReceiveUserId());
RequestBody requestBody = RequestBody.create(mediaType,jsonObject.toString());

Request request = new Request.Builder()
.url(p2pRouteRequestUrl)
.post(requestBody)
.build();

Response response = okHttpClient.newCall(request).execute() ;
if (!response.isSuccessful()){
throw new IOException("Unexpected code " + response);
}
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());

ResponseBody body = response.body();
Response response = null;
try {
String json = body.string() ;
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())){
LOGGER.error(p2PReqVO.getReceiveUserId() + ":" + StatusEnum.OFF_LINE.getMessage());
}

}catch (Exception e){
LOGGER.error("exception",e);
}finally {
body.close();
response.body().close();
}
}

@Override
public CIMServerResVO.ServerInfo getCIMServer(LoginReqVO loginReqVO) throws Exception {

JSONObject jsonObject = new JSONObject();
jsonObject.put("userId",loginReqVO.getUserId());
jsonObject.put("userName",loginReqVO.getUserName());
RequestBody requestBody = RequestBody.create(mediaType,jsonObject.toString());
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());

Request request = new Request.Builder()
.url(serverRouteLoginUrl)
.post(requestBody)
.build();

Response response = okHttpClient.newCall(request).execute() ;
if (!response.isSuccessful()){
throw new IOException("Unexpected code " + response);
}
CIMServerResVO cimServerResVO ;
ResponseBody body = response.body();
Response response = null;
CIMServerResVO cimServerResVO = null;
try {
String json = body.string();
response = (Response) routeApi.login(vo);
String json = response.body().string();
cimServerResVO = JSON.parseObject(json, CIMServerResVO.class);

//重复失败
Expand All @@ -152,61 +119,43 @@ public CIMServerResVO.ServerInfo getCIMServer(LoginReqVO loginReqVO) throws Exce
System.exit(-1);
}

}catch (Exception e){
LOGGER.error("exception",e);
}finally {
body.close();
response.body().close();
}



return cimServerResVO.getDataBody();
}

@Override
public List<OnlineUsersResVO.DataBodyBean> onlineUsers() throws Exception{
RouteApi routeApi = new ProxyManager<>(RouteApi.class, routeUrl, okHttpClient).getInstance();

JSONObject jsonObject = new JSONObject();
RequestBody requestBody = RequestBody.create(mediaType,jsonObject.toString());

Request request = new Request.Builder()
.url(onlineUserUrl)
.post(requestBody)
.build();

Response response = okHttpClient.newCall(request).execute() ;
if (!response.isSuccessful()){
throw new IOException("Unexpected code " + response);
}


ResponseBody body = response.body();
OnlineUsersResVO onlineUsersResVO ;
Response response = null;
OnlineUsersResVO onlineUsersResVO = null;
try {
String json = body.string() ;
response = (Response) routeApi.onlineUser();
String json = response.body().string() ;
onlineUsersResVO = JSON.parseObject(json, OnlineUsersResVO.class);

}catch (Exception e){
LOGGER.error("exception",e);
}finally {
body.close();
response.body().close();
}

return onlineUsersResVO.getDataBody();
}

@Override
public void offLine() {
JSONObject jsonObject = new JSONObject();
jsonObject.put("userId", appConfiguration.getUserId());
jsonObject.put("msg", "offLine");
RequestBody requestBody = RequestBody.create(mediaType, jsonObject.toString());

Request request = new Request.Builder()
.url(appConfiguration.getClearRouteUrl())
.post(requestBody)
.build();

RouteApi routeApi = new ProxyManager<>(RouteApi.class, routeUrl, okHttpClient).getInstance();
ChatReqVO vo = new ChatReqVO(appConfiguration.getUserId(), "offLine") ;
Response response = null;
try {
response = okHttpClient.newCall(request).execute();
} catch (IOException e) {
response = (Response) routeApi.offLine(vo);
} catch (Exception e) {
LOGGER.error("exception",e);
} finally {
response.body().close();
Expand Down
31 changes: 3 additions & 28 deletions cim-client/src/main/resources/application.properties
Original file line number Diff line number Diff line change
Expand Up @@ -13,36 +13,11 @@ cim.msg.logger.path = /opt/logs/cim/


###=======生产模拟======###
## 群发消息
#cim.group.route.request.url=http://45.78.28.220:8083/groupRoute
#
## 私聊消息
#cim.p2p.route.request.url=http://45.78.28.220:8083/p2pRoute
#
## 登录并获取服务器ip+port
#cim.server.route.request.url=http://45.78.28.220:8083/login
#
## 在线用户
#cim.server.online.user.url=http://45.78.28.220:8083/onlineUser
#
## 清除路由信息
#cim.clear.route.request.url=http://45.78.28.220:8083/offLine
#cim.route.url = http://45.78.28.220:8083/

###=======本地模拟======###
# 群发消息
cim.group.route.request.url=http://localhost:8083/groupRoute

# 私聊消息
cim.p2p.route.request.url=http://localhost:8083/p2pRoute

# 登录并获取服务器ip+port
cim.server.route.request.url=http://localhost:8083/login

# 在线用户
cim.server.online.user.url=http://localhost:8083/onlineUser

# 清除路由信息
cim.clear.route.request.url=http://localhost:8083/offLine
# route url suggested that this is Nginx address
cim.route.url = http://localhost:8083/

# 客户端唯一ID
cim.user.id=1586617710861
Expand Down
4 changes: 4 additions & 0 deletions cim-common/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -49,5 +49,9 @@
<artifactId>netty-all</artifactId>
<version>${netty.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
</dependency>
</dependencies>
</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
package com.crossoverjie.cim.common.core.proxy;

import com.alibaba.fastjson.JSONObject;
import com.crossoverjie.cim.common.exception.CIMException;
import com.crossoverjie.cim.common.util.HttpClient;
import okhttp3.OkHttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

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<T> {

private final static Logger LOGGER = LoggerFactory.getLogger(ProxyManager.class);

private Class<T> clazz;

private String url;

private OkHttpClient okHttpClient;

/**
*
* @param clazz Proxied interface
* @param url server provider url
* @param okHttpClient http client
*/
public ProxyManager(Class<T> 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 {
JSONObject jsonObject = new JSONObject();
String serverUrl = url + "/" + method.getName() ;

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));
}
}
return HttpClient.call(okHttpClient, jsonObject.toString(), serverUrl);
}
}
}
Loading