作者 crossoverJie

:recycle: Refactoring code.联调成功2

正在显示 29 个修改的文件 包含 687 行增加100 行删除
... ... @@ -4,7 +4,9 @@ import com.alibaba.fastjson.JSON;
import com.crossoverjie.cim.client.init.CIMClientHandleInitializer;
import com.crossoverjie.cim.client.service.RouteRequest;
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.common.constant.Constants;
import com.crossoverjie.cim.common.pojo.CustomProtocol;
import com.crossoverjie.cim.common.protocol.CIMRequestProto;
import io.netty.bootstrap.Bootstrap;
... ... @@ -38,6 +40,12 @@ public class CIMClient {
private EventLoopGroup group = new NioEventLoopGroup();
@Value("${cim.user.id}")
private long userId;
@Value("${cim.user.userName}")
private String userName;
@Value("${netty.server.port}")
private int nettyPort;
... ... @@ -52,10 +60,38 @@ public class CIMClient {
@PostConstruct
public void start() throws Exception {
//获取可以使用的服务器 ip+port
CIMServerResVO.ServerInfo cimServer = routeRequest.getCIMServer();
//登录 + 获取可以使用的服务器 ip+port
LoginReqVO loginReqVO = new LoginReqVO(userId,userName) ;
CIMServerResVO.ServerInfo cimServer = routeRequest.getCIMServer(loginReqVO);
LOGGER.info("cimServer=[{}]",cimServer.toString());
//启动客户端
startClient(cimServer);
//向服务端注册
loginCIMServer();
}
/**
* 向服务器注册
*/
private void loginCIMServer() {
CIMRequestProto.CIMReqProtocol login = CIMRequestProto.CIMReqProtocol.newBuilder()
.setRequestId(userId)
.setReqMsg(userName)
.setType(Constants.CommandType.LOGIN)
.build();
ChannelFuture future = channel.writeAndFlush(login);
future.addListener((ChannelFutureListener) channelFuture ->
LOGGER.info("注册成功={}", login.toString()));
}
/**
* 启动客户端
* @param cimServer
* @throws InterruptedException
*/
private void startClient(CIMServerResVO.ServerInfo cimServer) throws InterruptedException {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(group)
.channel(NioSocketChannel.class)
... ... @@ -104,6 +140,7 @@ public class CIMClient {
CIMRequestProto.CIMReqProtocol protocol = CIMRequestProto.CIMReqProtocol.newBuilder()
.setRequestId(googleProtocolVO.getRequestId())
.setReqMsg(googleProtocolVO.getMsg())
.setType(Constants.CommandType.MSG)
.build();
... ...
package com.crossoverjie.cim.client.config;
import com.crossoverjie.cim.common.constant.Constants;
import com.crossoverjie.cim.common.protocol.CIMRequestProto;
import okhttp3.OkHttpClient;
import org.springframework.beans.factory.annotation.Value;
... ... @@ -18,8 +19,8 @@ import java.util.concurrent.TimeUnit;
@Configuration
public class BeanConfig {
@Value("${client.request.id}")
private int requestId;
@Value("${cim.user.id}")
private long userId;
/**
... ... @@ -29,8 +30,9 @@ public class BeanConfig {
@Bean(value = "heartBeat")
public CIMRequestProto.CIMReqProtocol heartBeat() {
CIMRequestProto.CIMReqProtocol heart = CIMRequestProto.CIMReqProtocol.newBuilder()
.setRequestId(requestId)
.setRequestId(userId)
.setReqMsg("ping")
.setType(Constants.CommandType.PING)
.build();
return heart;
}
... ...
package com.crossoverjie.cim.client.service;
import com.crossoverjie.cim.client.vo.req.LoginReqVO;
import com.crossoverjie.cim.client.vo.res.CIMServerResVO;
/**
... ... @@ -23,5 +24,5 @@ public interface RouteRequest {
* @return 服务ip+port
* @throws Exception
*/
CIMServerResVO.ServerInfo getCIMServer() throws Exception;
CIMServerResVO.ServerInfo getCIMServer(LoginReqVO loginReqVO) throws Exception;
}
... ...
... ... @@ -3,6 +3,7 @@ package com.crossoverjie.cim.client.service.impl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
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.common.enums.StatusEnum;
import okhttp3.*;
... ... @@ -56,9 +57,11 @@ public class RouteRequestImpl implements RouteRequest {
}
@Override
public CIMServerResVO.ServerInfo getCIMServer() throws Exception {
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());
Request request = new Request.Builder()
... ...
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();
}
}
... ...
... ... @@ -15,10 +15,11 @@ logging.level.root=info
cim.group.route.request.url=http://localhost:8083/groupRoute
# 获取服务器ip+port
cim.server.route.request.url=http://localhost:8083/getCIMServer
cim.server.route.request.url=http://localhost:8083/login
# 客户端唯一ID
client.request.id=100
cim.user.id=1545574841528
cim.user.userName=zhangsan
# 关闭健康检查权限
... ...
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 org.junit.Test;
import org.junit.runner.RunWith;
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.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
/**
* Function:
*
* @author crossoverJie
* Date: 2018/12/23 22:39
* @since JDK 1.8
*/
@SpringBootTest(classes = CIMClientApplication.class)
@RunWith(SpringRunner.class)
public class RouteTest {
private final static Logger LOGGER = LoggerFactory.getLogger(RouteTest.class);
@Value("${cim.user.id}")
private long userId;
@Value("${cim.user.userName}")
private String userName;
@Autowired
private RouteRequest routeRequest ;
@Test
public void test() throws Exception {
LoginReqVO vo = new LoginReqVO(userId,userName) ;
CIMServerResVO.ServerInfo cimServer = routeRequest.getCIMServer(vo);
LOGGER.info("cimServer=[{}]",cimServer.toString());
}
}
... ...
... ... @@ -22,4 +22,23 @@ public class Constants {
public static final String COUNTER_CLIENT_PUSH_COUNT = "counter.client.push.count" ;
public static class CommandType{
/**
* 登录
*/
public static final int LOGIN = 1 ;
/**
* 业务消息
*/
public static final int MSG = 2 ;
/**
* 业务消息
*/
public static final int PING = 3 ;
}
}
... ...
... ... @@ -19,13 +19,13 @@ public final class CIMRequestProto {
com.google.protobuf.MessageOrBuilder {
/**
* <code>required int32 requestId = 2;</code>
* <code>required int64 requestId = 2;</code>
*/
boolean hasRequestId();
/**
* <code>required int32 requestId = 2;</code>
* <code>required int64 requestId = 2;</code>
*/
int getRequestId();
long getRequestId();
/**
* <code>required string reqMsg = 1;</code>
... ... @@ -40,6 +40,15 @@ public final class CIMRequestProto {
*/
com.google.protobuf.ByteString
getReqMsgBytes();
/**
* <code>required int32 type = 3;</code>
*/
boolean hasType();
/**
* <code>required int32 type = 3;</code>
*/
int getType();
}
/**
* Protobuf type {@code protocol.CIMReqProtocol}
... ... @@ -54,8 +63,9 @@ public final class CIMRequestProto {
super(builder);
}
private CIMReqProtocol() {
requestId_ = 0;
requestId_ = 0L;
reqMsg_ = "";
type_ = 0;
}
@Override
... ... @@ -97,7 +107,12 @@ public final class CIMRequestProto {
}
case 16: {
bitField0_ |= 0x00000001;
requestId_ = input.readInt32();
requestId_ = input.readInt64();
break;
}
case 24: {
bitField0_ |= 0x00000004;
type_ = input.readInt32();
break;
}
}
... ... @@ -126,17 +141,17 @@ public final class CIMRequestProto {
private int bitField0_;
public static final int REQUESTID_FIELD_NUMBER = 2;
private int requestId_;
private long requestId_;
/**
* <code>required int32 requestId = 2;</code>
* <code>required int64 requestId = 2;</code>
*/
public boolean hasRequestId() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
/**
* <code>required int32 requestId = 2;</code>
* <code>required int64 requestId = 2;</code>
*/
public int getRequestId() {
public long getRequestId() {
return requestId_;
}
... ... @@ -182,6 +197,21 @@ public final class CIMRequestProto {
}
}
public static final int TYPE_FIELD_NUMBER = 3;
private int type_;
/**
* <code>required int32 type = 3;</code>
*/
public boolean hasType() {
return ((bitField0_ & 0x00000004) == 0x00000004);
}
/**
* <code>required int32 type = 3;</code>
*/
public int getType() {
return type_;
}
private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
... ... @@ -196,6 +226,10 @@ public final class CIMRequestProto {
memoizedIsInitialized = 0;
return false;
}
if (!hasType()) {
memoizedIsInitialized = 0;
return false;
}
memoizedIsInitialized = 1;
return true;
}
... ... @@ -206,7 +240,10 @@ public final class CIMRequestProto {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, reqMsg_);
}
if (((bitField0_ & 0x00000001) == 0x00000001)) {
output.writeInt32(2, requestId_);
output.writeInt64(2, requestId_);
}
if (((bitField0_ & 0x00000004) == 0x00000004)) {
output.writeInt32(3, type_);
}
unknownFields.writeTo(output);
}
... ... @@ -221,7 +258,11 @@ public final class CIMRequestProto {
}
if (((bitField0_ & 0x00000001) == 0x00000001)) {
size += com.google.protobuf.CodedOutputStream
.computeInt32Size(2, requestId_);
.computeInt64Size(2, requestId_);
}
if (((bitField0_ & 0x00000004) == 0x00000004)) {
size += com.google.protobuf.CodedOutputStream
.computeInt32Size(3, type_);
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
... ... @@ -249,6 +290,11 @@ public final class CIMRequestProto {
result = result && getReqMsg()
.equals(other.getReqMsg());
}
result = result && (hasType() == other.hasType());
if (hasType()) {
result = result && (getType()
== other.getType());
}
result = result && unknownFields.equals(other.unknownFields);
return result;
}
... ... @@ -262,12 +308,17 @@ public final class CIMRequestProto {
hash = (19 * hash) + getDescriptor().hashCode();
if (hasRequestId()) {
hash = (37 * hash) + REQUESTID_FIELD_NUMBER;
hash = (53 * hash) + getRequestId();
hash = (53 * hash) + com.google.protobuf.Internal.hashLong(
getRequestId());
}
if (hasReqMsg()) {
hash = (37 * hash) + REQMSG_FIELD_NUMBER;
hash = (53 * hash) + getReqMsg().hashCode();
}
if (hasType()) {
hash = (37 * hash) + TYPE_FIELD_NUMBER;
hash = (53 * hash) + getType();
}
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
... ... @@ -397,10 +448,12 @@ public final class CIMRequestProto {
}
public Builder clear() {
super.clear();
requestId_ = 0;
requestId_ = 0L;
bitField0_ = (bitField0_ & ~0x00000001);
reqMsg_ = "";
bitField0_ = (bitField0_ & ~0x00000002);
type_ = 0;
bitField0_ = (bitField0_ & ~0x00000004);
return this;
}
... ... @@ -433,6 +486,10 @@ public final class CIMRequestProto {
to_bitField0_ |= 0x00000002;
}
result.reqMsg_ = reqMsg_;
if (((from_bitField0_ & 0x00000004) == 0x00000004)) {
to_bitField0_ |= 0x00000004;
}
result.type_ = type_;
result.bitField0_ = to_bitField0_;
onBuilt();
return result;
... ... @@ -483,6 +540,9 @@ public final class CIMRequestProto {
reqMsg_ = other.reqMsg_;
onChanged();
}
if (other.hasType()) {
setType(other.getType());
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
... ... @@ -495,6 +555,9 @@ public final class CIMRequestProto {
if (!hasReqMsg()) {
return false;
}
if (!hasType()) {
return false;
}
return true;
}
... ... @@ -517,34 +580,34 @@ public final class CIMRequestProto {
}
private int bitField0_;
private int requestId_ ;
private long requestId_ ;
/**
* <code>required int32 requestId = 2;</code>
* <code>required int64 requestId = 2;</code>
*/
public boolean hasRequestId() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
/**
* <code>required int32 requestId = 2;</code>
* <code>required int64 requestId = 2;</code>
*/
public int getRequestId() {
public long getRequestId() {
return requestId_;
}
/**
* <code>required int32 requestId = 2;</code>
* <code>required int64 requestId = 2;</code>
*/
public Builder setRequestId(int value) {
public Builder setRequestId(long value) {
bitField0_ |= 0x00000001;
requestId_ = value;
onChanged();
return this;
}
/**
* <code>required int32 requestId = 2;</code>
* <code>required int64 requestId = 2;</code>
*/
public Builder clearRequestId() {
bitField0_ = (bitField0_ & ~0x00000001);
requestId_ = 0;
requestId_ = 0L;
onChanged();
return this;
}
... ... @@ -624,6 +687,38 @@ public final class CIMRequestProto {
onChanged();
return this;
}
private int type_ ;
/**
* <code>required int32 type = 3;</code>
*/
public boolean hasType() {
return ((bitField0_ & 0x00000004) == 0x00000004);
}
/**
* <code>required int32 type = 3;</code>
*/
public int getType() {
return type_;
}
/**
* <code>required int32 type = 3;</code>
*/
public Builder setType(int value) {
bitField0_ |= 0x00000004;
type_ = value;
onChanged();
return this;
}
/**
* <code>required int32 type = 3;</code>
*/
public Builder clearType() {
bitField0_ = (bitField0_ & ~0x00000004);
type_ = 0;
onChanged();
return this;
}
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
... ... @@ -687,10 +782,10 @@ public final class CIMRequestProto {
descriptor;
static {
String[] descriptorData = {
"\n\026BaseRequestProto.proto\022\010protocol\"3\n\016CI" +
"MReqProtocol\022\021\n\trequestId\030\002 \002(\005\022\016\n\006reqMs" +
"g\030\001 \002(\tB7\n$com.crossoverjie.cim.common.p" +
"rotocolB\017CIMRequestProto"
"\n\026BaseRequestProto.proto\022\010protocol\"A\n\016CI" +
"MReqProtocol\022\021\n\trequestId\030\002 \002(\003\022\016\n\006reqMs" +
"g\030\001 \002(\t\022\014\n\004type\030\003 \002(\005B7\n$com.crossoverji" +
"e.cim.common.protocolB\017CIMRequestProto"
};
com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner =
new com.google.protobuf.Descriptors.FileDescriptor. InternalDescriptorAssigner() {
... ... @@ -709,7 +804,7 @@ public final class CIMRequestProto {
internal_static_protocol_CIMReqProtocol_fieldAccessorTable = new
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_protocol_CIMReqProtocol_descriptor,
new String[] { "RequestId", "ReqMsg", });
new String[] { "RequestId", "ReqMsg", "Type", });
}
// @@protoc_insertion_point(outer_class_scope)
... ...
... ... @@ -19,13 +19,13 @@ public final class CIMResponseProto {
com.google.protobuf.MessageOrBuilder {
/**
* <code>required int32 responseId = 2;</code>
* <code>required int64 responseId = 2;</code>
*/
boolean hasResponseId();
/**
* <code>required int32 responseId = 2;</code>
* <code>required int64 responseId = 2;</code>
*/
int getResponseId();
long getResponseId();
/**
* <code>required string resMsg = 1;</code>
... ... @@ -54,7 +54,7 @@ public final class CIMResponseProto {
super(builder);
}
private CIMResProtocol() {
responseId_ = 0;
responseId_ = 0L;
resMsg_ = "";
}
... ... @@ -97,7 +97,7 @@ public final class CIMResponseProto {
}
case 16: {
bitField0_ |= 0x00000001;
responseId_ = input.readInt32();
responseId_ = input.readInt64();
break;
}
}
... ... @@ -126,17 +126,17 @@ public final class CIMResponseProto {
private int bitField0_;
public static final int RESPONSEID_FIELD_NUMBER = 2;
private int responseId_;
private long responseId_;
/**
* <code>required int32 responseId = 2;</code>
* <code>required int64 responseId = 2;</code>
*/
public boolean hasResponseId() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
/**
* <code>required int32 responseId = 2;</code>
* <code>required int64 responseId = 2;</code>
*/
public int getResponseId() {
public long getResponseId() {
return responseId_;
}
... ... @@ -206,7 +206,7 @@ public final class CIMResponseProto {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, resMsg_);
}
if (((bitField0_ & 0x00000001) == 0x00000001)) {
output.writeInt32(2, responseId_);
output.writeInt64(2, responseId_);
}
unknownFields.writeTo(output);
}
... ... @@ -221,7 +221,7 @@ public final class CIMResponseProto {
}
if (((bitField0_ & 0x00000001) == 0x00000001)) {
size += com.google.protobuf.CodedOutputStream
.computeInt32Size(2, responseId_);
.computeInt64Size(2, responseId_);
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
... ... @@ -262,7 +262,8 @@ public final class CIMResponseProto {
hash = (19 * hash) + getDescriptor().hashCode();
if (hasResponseId()) {
hash = (37 * hash) + RESPONSEID_FIELD_NUMBER;
hash = (53 * hash) + getResponseId();
hash = (53 * hash) + com.google.protobuf.Internal.hashLong(
getResponseId());
}
if (hasResMsg()) {
hash = (37 * hash) + RESMSG_FIELD_NUMBER;
... ... @@ -397,7 +398,7 @@ public final class CIMResponseProto {
}
public Builder clear() {
super.clear();
responseId_ = 0;
responseId_ = 0L;
bitField0_ = (bitField0_ & ~0x00000001);
resMsg_ = "";
bitField0_ = (bitField0_ & ~0x00000002);
... ... @@ -517,34 +518,34 @@ public final class CIMResponseProto {
}
private int bitField0_;
private int responseId_ ;
private long responseId_ ;
/**
* <code>required int32 responseId = 2;</code>
* <code>required int64 responseId = 2;</code>
*/
public boolean hasResponseId() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
/**
* <code>required int32 responseId = 2;</code>
* <code>required int64 responseId = 2;</code>
*/
public int getResponseId() {
public long getResponseId() {
return responseId_;
}
/**
* <code>required int32 responseId = 2;</code>
* <code>required int64 responseId = 2;</code>
*/
public Builder setResponseId(int value) {
public Builder setResponseId(long value) {
bitField0_ |= 0x00000001;
responseId_ = value;
onChanged();
return this;
}
/**
* <code>required int32 responseId = 2;</code>
* <code>required int64 responseId = 2;</code>
*/
public Builder clearResponseId() {
bitField0_ = (bitField0_ & ~0x00000001);
responseId_ = 0;
responseId_ = 0L;
onChanged();
return this;
}
... ... @@ -688,7 +689,7 @@ public final class CIMResponseProto {
static {
String[] descriptorData = {
"\n\027BaseResponseProto.proto\022\010protocol\"4\n\016C" +
"IMResProtocol\022\022\n\nresponseId\030\002 \002(\005\022\016\n\006res" +
"IMResProtocol\022\022\n\nresponseId\030\002 \002(\003\022\016\n\006res" +
"Msg\030\001 \002(\tB8\n$com.crossoverjie.cim.common" +
".protocolB\020CIMResponseProto"
};
... ...
... ... @@ -13,7 +13,7 @@ public class ProtocolUtil {
public static void main(String[] args) throws InvalidProtocolBufferException {
CIMRequestProto.CIMReqProtocol protocol = CIMRequestProto.CIMReqProtocol.newBuilder()
.setRequestId(123)
.setRequestId(123L)
.setReqMsg("你好啊")
.build();
... ...
... ... @@ -35,6 +35,11 @@
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
... ...
... ... @@ -7,6 +7,10 @@ import org.I0Itec.zkclient.ZkClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
* Function:
... ... @@ -36,4 +40,19 @@ public class BeanConfig {
}
});
}
/**
* Redis bean
* @param factory
* @return
*/
@Bean
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
StringRedisTemplate redisTemplate = new StringRedisTemplate(factory);
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new StringRedisSerializer());
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
}
... ...
package com.crossoverjie.cim.route.constant;
/**
* Function:
*
* @author crossoverJie
* Date: 2018/9/10 14:07
* @since JDK 1.8
*/
public final class Constant {
/**
* 账号前缀
*/
public final static String ACCOUNT_PREFIX = "cim-account:";
}
... ...
... ... @@ -4,9 +4,13 @@ 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.cache.ServerCache;
import com.crossoverjie.cim.route.vo.req.GroupRequest;
import com.crossoverjie.cim.route.vo.req.P2PRequest;
import com.crossoverjie.cim.route.service.AccountService;
import com.crossoverjie.cim.route.vo.req.GroupReqVO;
import com.crossoverjie.cim.route.vo.req.LoginReqVO;
import com.crossoverjie.cim.route.vo.req.P2PReqVO;
import com.crossoverjie.cim.route.vo.req.RegisterInfoReqVO;
import com.crossoverjie.cim.route.vo.res.CIMServerResVO;
import com.crossoverjie.cim.route.vo.res.RegisterInfoResVO;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
... ... @@ -32,13 +36,16 @@ public class RouteController {
@Autowired
private ServerCache serverCache ;
@Autowired
private AccountService accountService;
@ApiOperation("群聊 API")
@RequestMapping(value = "groupRoute",method = RequestMethod.POST)
@ResponseBody()
public BaseResponse<NULLBody> groupRoute(@RequestBody GroupRequest groupRequest){
public BaseResponse<NULLBody> groupRoute(@RequestBody GroupReqVO groupReqVO){
BaseResponse<NULLBody> res = new BaseResponse();
LOGGER.info("msg=[{}]",groupRequest.toString());
LOGGER.info("msg=[{}]", groupReqVO.toString());
res.setCode(StatusEnum.SUCCESS.getCode()) ;
res.setMessage(StatusEnum.SUCCESS.getMessage()) ;
... ... @@ -54,7 +61,7 @@ public class RouteController {
@ApiOperation("私聊 API")
@RequestMapping(value = "p2pRoute",method = RequestMethod.POST)
@ResponseBody()
public BaseResponse<NULLBody> p2pRoute(@RequestBody P2PRequest p2pRequest){
public BaseResponse<NULLBody> p2pRoute(@RequestBody P2PReqVO p2pRequest){
BaseResponse<NULLBody> res = new BaseResponse();
res.setCode(StatusEnum.SUCCESS.getCode()) ;
... ... @@ -66,12 +73,15 @@ public class RouteController {
* 获取一台 CIM server
* @return
*/
@ApiOperation("获取服务器")
@RequestMapping(value = "getCIMServer",method = RequestMethod.POST)
@ApiOperation("登录并获取服务器")
@RequestMapping(value = "login",method = RequestMethod.POST)
@ResponseBody()
public BaseResponse<CIMServerResVO> getCIMServer(){
public BaseResponse<CIMServerResVO> login(@RequestBody LoginReqVO loginReqVO) throws Exception {
BaseResponse<CIMServerResVO> res = new BaseResponse();
//登录校验
boolean login = accountService.login(loginReqVO);
if (login){
String server = serverCache.selectServer();
String[] serverInfo = server.split(":");
CIMServerResVO vo = new CIMServerResVO(serverInfo[0],Integer.parseInt(serverInfo[1])) ;
... ... @@ -79,6 +89,31 @@ public class RouteController {
res.setDataBody(vo);
res.setCode(StatusEnum.SUCCESS.getCode()) ;
res.setMessage(StatusEnum.SUCCESS.getMessage()) ;
}else {
res.setCode(StatusEnum.FAIL.getCode()) ;
res.setMessage(StatusEnum.FAIL.getMessage()) ;
}
return res ;
}
/**
* 注册账号
* @return
*/
@ApiOperation("注册账号")
@RequestMapping(value = "registerAccount",method = RequestMethod.POST)
@ResponseBody()
public BaseResponse<RegisterInfoResVO> registerAccount(@RequestBody RegisterInfoReqVO registerInfoReqVO) throws Exception {
BaseResponse<RegisterInfoResVO> res = new BaseResponse();
long userId = System.currentTimeMillis();
RegisterInfoResVO info = new RegisterInfoResVO(userId,registerInfoReqVO.getUserName()) ;
info = accountService.registerAccount(info);
res.setDataBody(info);
res.setCode(StatusEnum.SUCCESS.getCode()) ;
res.setMessage(StatusEnum.SUCCESS.getMessage()) ;
return res ;
}
... ...
package com.crossoverjie.cim.route.service;
import com.crossoverjie.cim.route.vo.req.LoginReqVO;
import com.crossoverjie.cim.route.vo.res.RegisterInfoResVO;
/**
* Function: 账户服务
*
* @author crossoverJie
* Date: 2018/12/23 21:57
* @since JDK 1.8
*/
public interface AccountService {
/**
* 注册用户
* @param info 用户信息
* @return
* @throws Exception
*/
RegisterInfoResVO registerAccount(RegisterInfoResVO info) throws Exception;
/**
* 登录服务
* @param loginReqVO 登录信息
* @return true 成功 false 失败
* @throws Exception
*/
boolean login(LoginReqVO loginReqVO) throws Exception ;
}
... ...
package com.crossoverjie.cim.route.service.impl;
import com.crossoverjie.cim.route.service.AccountService;
import com.crossoverjie.cim.route.vo.req.LoginReqVO;
import com.crossoverjie.cim.route.vo.res.RegisterInfoResVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import static com.crossoverjie.cim.route.constant.Constant.ACCOUNT_PREFIX;
/**
* Function:
*
* @author crossoverJie
* Date: 2018/12/23 21:58
* @since JDK 1.8
*/
@Service
public class AccountServiceRedisImpl implements AccountService {
private final static Logger LOGGER = LoggerFactory.getLogger(AccountServiceRedisImpl.class);
@Autowired
private RedisTemplate<String, String> redisTemplate;
@Override
public RegisterInfoResVO registerAccount(RegisterInfoResVO info) {
String key = ACCOUNT_PREFIX + info.getUserId();
String name = redisTemplate.opsForValue().get(info.getUserName()) ;
if (null == name){
//为了方便查询,冗余存一份
redisTemplate.opsForValue().set(key, info.getUserName());
redisTemplate.opsForValue().set(info.getUserName(),key);
}else {
long userId = Long.parseLong(name.split(":")[1]);
info.setUserId(userId);
info.setUserName(info.getUserName());
}
return info ;
}
@Override
public boolean login(LoginReqVO loginReqVO) throws Exception {
String key = ACCOUNT_PREFIX + loginReqVO.getUserId();
String userName = redisTemplate.opsForValue().get(key);
if (null == userName){
return false ;
}
if (!userName.equals(loginReqVO.getUserName())){
return false ;
}
return true ;
}
}
... ...
... ... @@ -12,7 +12,7 @@ import javax.validation.constraints.NotNull;
* Date: 2018/05/21 15:56
* @since JDK 1.8
*/
public class GroupRequest extends BaseRequest {
public class GroupReqVO extends BaseRequest {
@NotNull(message = "msg 不能为空")
@ApiModelProperty(required = true, value = "msg", example = "hello")
... ...
package com.crossoverjie.cim.route.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 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();
}
}
... ...
... ... @@ -12,7 +12,7 @@ import javax.validation.constraints.NotNull;
* Date: 2018/05/21 15:56
* @since JDK 1.8
*/
public class P2PRequest extends BaseRequest {
public class P2PReqVO extends BaseRequest {
@NotNull(message = "msg 不能为空")
@ApiModelProperty(required = true, value = "msg", example = "hello")
... ...
package com.crossoverjie.cim.route.vo.req;
import com.crossoverjie.cim.common.req.BaseRequest;
import io.swagger.annotations.ApiModelProperty;
import javax.validation.constraints.NotNull;
/**
* Function:
*
* @author crossoverJie
* Date: 2018/12/23 22:04
* @since JDK 1.8
*/
public class RegisterInfoReqVO extends BaseRequest {
@NotNull(message = "用户名不能为空")
@ApiModelProperty(required = true, value = "userName", example = "zhangsan")
private String userName ;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
@Override
public String toString() {
return "RegisterInfoReqVO{" +
"userName='" + userName + '\'' +
"} " + super.toString();
}
}
... ...
package com.crossoverjie.cim.route.vo.res;
import java.io.Serializable;
/**
* Function:
*
* @author crossoverJie
* Date: 2018/12/23 21:54
* @since JDK 1.8
*/
public class RegisterInfoResVO implements Serializable{
private Long userId ;
private String userName ;
public RegisterInfoResVO(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 "RegisterInfo{" +
"userId=" + userId +
", userName='" + userName + '\'' +
'}';
}
}
... ...
... ... @@ -18,3 +18,13 @@ app.zk.addr=47.98.194.60:2181
# zk 注册根节点
app.zk.root=/route
# Redis 配置
spring.redis.host=47.98.194.60
spring.redis.port=6379
spring.redis.pool.max-active=100
spring.redis.pool.max-idle=100
spring.redis.pool.max-wait=1000
spring.redis.pool.min-idle=10
... ...
import com.crossoverjie.cim.route.RouteApplication;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;
/**
* Function:
*
* @author crossoverJie
* Date: 2018/12/23 21:40
* @since JDK 1.8
*/
@SpringBootTest(classes = RouteApplication.class)
@RunWith(SpringRunner.class)
public class RedisTest {
@Autowired
private RedisTemplate<String,String> redisTemplate ;
@Test
public void test(){
redisTemplate.opsForValue().set("test","test") ;
String test = redisTemplate.opsForValue().get("test");
System.out.println("====" + test);
}
}
... ...
package com.crossoverjie.cim.server.endpoint;
import com.crossoverjie.cim.server.util.NettySocketHolder;
import com.crossoverjie.cim.server.util.SessionSocketHolder;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.springframework.boot.actuate.endpoint.AbstractEndpoint;
... ... @@ -27,6 +27,6 @@ public class CustomEndpoint extends AbstractEndpoint<Map<Long,NioSocketChannel>>
@Override
public Map<Long, NioSocketChannel> invoke() {
return NettySocketHolder.getMAP();
return SessionSocketHolder.getMAP();
}
}
... ...
package com.crossoverjie.cim.server.handle;
import com.crossoverjie.cim.common.constant.Constants;
import com.crossoverjie.cim.common.protocol.CIMRequestProto;
import com.crossoverjie.cim.common.protocol.CIMResponseProto;
import com.crossoverjie.cim.server.util.NettySocketHolder;
import com.crossoverjie.cim.server.util.SessionSocketHolder;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
... ... @@ -30,28 +30,22 @@ public class CIMServerHandle extends SimpleChannelInboundHandler<CIMRequestProto
*/
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
LOGGER.info("客户端断开");
NettySocketHolder.remove((NioSocketChannel) ctx.channel());
String userName = SessionSocketHolder.getUserName((NioSocketChannel) ctx.channel());
LOGGER.info("用户[{}]断开",userName);
SessionSocketHolder.remove((NioSocketChannel) ctx.channel());
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
LOGGER.info("有客户端连上来了。。");
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, CIMRequestProto.CIMReqProtocol msg) throws Exception {
LOGGER.info("收到msg={}", msg.getReqMsg());
if (999 == msg.getRequestId()){
CIMResponseProto.CIMResProtocol responseProtocol = CIMResponseProto.CIMResProtocol.newBuilder()
.setResponseId(1000)
.setResMsg("服务端响应")
.build();
ctx.writeAndFlush(responseProtocol) ;
}
LOGGER.info("收到msg={}", msg.toString());
if (msg.getType() == Constants.CommandType.LOGIN){
//保存客户端与 Channel 之间的关系
NettySocketHolder.put((long) msg.getRequestId(),(NioSocketChannel)ctx.channel()) ;
SessionSocketHolder.put(msg.getRequestId(),(NioSocketChannel)ctx.channel()) ;
SessionSocketHolder.saveSession(msg.getRequestId(),msg.getReqMsg());
LOGGER.info("客户端[{}]注册成功",msg.getReqMsg());
}
}
}
... ...
... ... @@ -4,7 +4,7 @@ import com.alibaba.fastjson.JSON;
import com.crossoverjie.cim.common.pojo.CustomProtocol;
import com.crossoverjie.cim.common.protocol.CIMRequestProto;
import com.crossoverjie.cim.server.init.CIMServerInitializer;
import com.crossoverjie.cim.server.util.NettySocketHolder;
import com.crossoverjie.cim.server.util.SessionSocketHolder;
import com.crossoverjie.cim.server.vo.req.SendMsgReqVO;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.Unpooled;
... ... @@ -86,7 +86,7 @@ public class CIMServer {
* @param customProtocol
*/
public void sendMsg(CustomProtocol customProtocol) {
NioSocketChannel socketChannel = NettySocketHolder.get(customProtocol.getId());
NioSocketChannel socketChannel = SessionSocketHolder.get(customProtocol.getId());
if (null == socketChannel) {
throw new NullPointerException("没有[" + customProtocol.getId() + "]的socketChannel");
... ... @@ -102,7 +102,7 @@ public class CIMServer {
* @param sendMsgReqVO 消息
*/
public void sendGoogleProtoMsg(SendMsgReqVO sendMsgReqVO){
NioSocketChannel socketChannel = NettySocketHolder.get(sendMsgReqVO.getId());
NioSocketChannel socketChannel = SessionSocketHolder.get(sendMsgReqVO.getId());
if (null == socketChannel) {
throw new NullPointerException("没有[" + sendMsgReqVO.getId() + "]的socketChannel");
... ...
package com.crossoverjie.cim.server.util;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import java.util.Map;
... ... @@ -14,22 +12,46 @@ import java.util.concurrent.ConcurrentHashMap;
* Date: 22/05/2018 18:33
* @since JDK 1.8
*/
public class NettySocketHolder {
private static final Map<Long, NioSocketChannel> MAP = new ConcurrentHashMap<>(16);
public class SessionSocketHolder {
private static final Map<Long, NioSocketChannel> CHANNEL_MAP = new ConcurrentHashMap<>(16);
private static final Map<Long, String> SESSION_MAP = new ConcurrentHashMap<>(16);
public static void saveSession(Long userId,String userName){
SESSION_MAP.put(userId, userName);
}
public static void put(Long id, NioSocketChannel socketChannel) {
MAP.put(id, socketChannel);
CHANNEL_MAP.put(id, socketChannel);
}
public static NioSocketChannel get(Long id) {
return MAP.get(id);
return CHANNEL_MAP.get(id);
}
public static Map<Long, NioSocketChannel> getMAP() {
return MAP;
return CHANNEL_MAP;
}
public static void remove(NioSocketChannel nioSocketChannel) {
MAP.entrySet().stream().filter(entry -> entry.getValue() == nioSocketChannel).forEach(entry -> MAP.remove(entry.getKey()));
CHANNEL_MAP.entrySet().stream().filter(entry -> entry.getValue() == nioSocketChannel).forEach(entry -> CHANNEL_MAP.remove(entry.getKey()));
}
/**
* 获取注册用户信息
* @param nioSocketChannel
* @return
*/
public static String getUserName(NioSocketChannel nioSocketChannel){
for (Map.Entry<Long, NioSocketChannel> entry : CHANNEL_MAP.entrySet()) {
NioSocketChannel value = entry.getValue();
if (nioSocketChannel == value){
Long key = entry.getKey();
String userName = SESSION_MAP.get(key);
return userName ;
}
}
return null;
}
}
... ...
... ... @@ -11,7 +11,7 @@
<properties>
<junit.version>4.11</junit.version>
<junit.version>4.12</junit.version>
<netty.version>4.1.21.Final</netty.version>
<logback.version>1.0.13</logback.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
... ...