作者 crossoverJie

:recycle: Refactoring code.联调成功 群发,完善

正在显示 22 个修改的文件 包含 156 行增加195 行删除
@@ -3,7 +3,6 @@ package com.crossoverjie.cim.client; @@ -3,7 +3,6 @@ package com.crossoverjie.cim.client;
3 import com.crossoverjie.cim.client.scanner.Scan; 3 import com.crossoverjie.cim.client.scanner.Scan;
4 import org.slf4j.Logger; 4 import org.slf4j.Logger;
5 import org.slf4j.LoggerFactory; 5 import org.slf4j.LoggerFactory;
6 -import org.springframework.beans.factory.annotation.Value;  
7 import org.springframework.boot.CommandLineRunner; 6 import org.springframework.boot.CommandLineRunner;
8 import org.springframework.boot.SpringApplication; 7 import org.springframework.boot.SpringApplication;
9 import org.springframework.boot.autoconfigure.SpringBootApplication; 8 import org.springframework.boot.autoconfigure.SpringBootApplication;
@@ -16,17 +15,14 @@ public class CIMClientApplication implements CommandLineRunner{ @@ -16,17 +15,14 @@ public class CIMClientApplication implements CommandLineRunner{
16 15
17 private final static Logger LOGGER = LoggerFactory.getLogger(CIMClientApplication.class); 16 private final static Logger LOGGER = LoggerFactory.getLogger(CIMClientApplication.class);
18 17
19 - @Value("${cim.user.id}")  
20 - private long userId;  
21 -  
22 public static void main(String[] args) { 18 public static void main(String[] args) {
23 SpringApplication.run(CIMClientApplication.class, args); 19 SpringApplication.run(CIMClientApplication.class, args);
24 - LOGGER.info("启动 Client 成功"); 20 + LOGGER.info("启动 Client 服务成功");
25 } 21 }
26 22
27 @Override 23 @Override
28 public void run(String... args) throws Exception { 24 public void run(String... args) throws Exception {
29 - Scan scan = new Scan(userId) ; 25 + Scan scan = new Scan() ;
30 Thread thread = new Thread(scan); 26 Thread thread = new Thread(scan);
31 thread.setName("scan-thread"); 27 thread.setName("scan-thread");
32 thread.start(); 28 thread.start();
1 package com.crossoverjie.cim.client.client; 1 package com.crossoverjie.cim.client.client;
2 2
3 -import com.alibaba.fastjson.JSON;  
4 import com.crossoverjie.cim.client.init.CIMClientHandleInitializer; 3 import com.crossoverjie.cim.client.init.CIMClientHandleInitializer;
5 import com.crossoverjie.cim.client.service.RouteRequest; 4 import com.crossoverjie.cim.client.service.RouteRequest;
6 import com.crossoverjie.cim.client.vo.req.GoogleProtocolVO; 5 import com.crossoverjie.cim.client.vo.req.GoogleProtocolVO;
7 import com.crossoverjie.cim.client.vo.req.LoginReqVO; 6 import com.crossoverjie.cim.client.vo.req.LoginReqVO;
8 import com.crossoverjie.cim.client.vo.res.CIMServerResVO; 7 import com.crossoverjie.cim.client.vo.res.CIMServerResVO;
9 import com.crossoverjie.cim.common.constant.Constants; 8 import com.crossoverjie.cim.common.constant.Constants;
10 -import com.crossoverjie.cim.common.pojo.CustomProtocol;  
11 import com.crossoverjie.cim.common.protocol.CIMRequestProto; 9 import com.crossoverjie.cim.common.protocol.CIMRequestProto;
12 import io.netty.bootstrap.Bootstrap; 10 import io.netty.bootstrap.Bootstrap;
13 import io.netty.buffer.ByteBuf; 11 import io.netty.buffer.ByteBuf;
@@ -99,17 +97,6 @@ public class CIMClient { @@ -99,17 +97,6 @@ public class CIMClient {
99 } 97 }
100 98
101 /** 99 /**
102 - * 发送消息  
103 - *  
104 - * @param customProtocol  
105 - */  
106 - public void sendMsg(CustomProtocol customProtocol) {  
107 - ChannelFuture future = channel.writeAndFlush(customProtocol);  
108 - future.addListener((ChannelFutureListener) channelFuture ->  
109 - LOGGER.info("客户端手动发消息成功={}", JSON.toJSONString(customProtocol)));  
110 -  
111 - }  
112 - /**  
113 * 发送消息字符串 100 * 发送消息字符串
114 * 101 *
115 * @param msg 102 * @param msg
  1 +package com.crossoverjie.cim.client.config;
  2 +
  3 +import org.springframework.beans.factory.annotation.Value;
  4 +import org.springframework.stereotype.Component;
  5 +
  6 +/**
  7 + * Function:
  8 + *
  9 + * @author crossoverJie
  10 + * Date: 2018/8/24 01:43
  11 + * @since JDK 1.8
  12 + */
  13 +@Component
  14 +public class AppConfiguration {
  15 +
  16 + @Value("${cim.user.id}")
  17 + private Long userId;
  18 +
  19 + @Value("${cim.user.userName}")
  20 + private String userName;
  21 +
  22 + public Long getUserId() {
  23 + return userId;
  24 + }
  25 +
  26 + public void setUserId(Long userId) {
  27 + this.userId = userId;
  28 + }
  29 +
  30 + public String getUserName() {
  31 + return userName;
  32 + }
  33 +
  34 + public void setUserName(String userName) {
  35 + this.userName = userName;
  36 + }
  37 +}
@@ -9,7 +9,6 @@ import com.crossoverjie.cim.client.vo.req.StringReqVO; @@ -9,7 +9,6 @@ import com.crossoverjie.cim.client.vo.req.StringReqVO;
9 import com.crossoverjie.cim.client.vo.res.SendMsgResVO; 9 import com.crossoverjie.cim.client.vo.res.SendMsgResVO;
10 import com.crossoverjie.cim.common.constant.Constants; 10 import com.crossoverjie.cim.common.constant.Constants;
11 import com.crossoverjie.cim.common.enums.StatusEnum; 11 import com.crossoverjie.cim.common.enums.StatusEnum;
12 -import com.crossoverjie.cim.common.pojo.CustomProtocol;  
13 import com.crossoverjie.cim.common.res.BaseResponse; 12 import com.crossoverjie.cim.common.res.BaseResponse;
14 import com.crossoverjie.cim.common.res.NULLBody; 13 import com.crossoverjie.cim.common.res.NULLBody;
15 import io.swagger.annotations.ApiOperation; 14 import io.swagger.annotations.ApiOperation;
@@ -46,28 +45,6 @@ public class IndexController { @@ -46,28 +45,6 @@ public class IndexController {
46 @Autowired 45 @Autowired
47 private RouteRequest routeRequest ; 46 private RouteRequest routeRequest ;
48 47
49 - /**  
50 - * 向服务端发消息  
51 - * @param sendMsgReqVO  
52 - * @return  
53 - */  
54 - @ApiOperation("客户端发送消息")  
55 - @RequestMapping(value = "sendMsg",method = RequestMethod.POST)  
56 - @ResponseBody()  
57 - public BaseResponse<SendMsgResVO> sendMsg(@RequestBody SendMsgReqVO sendMsgReqVO){  
58 - BaseResponse<SendMsgResVO> res = new BaseResponse();  
59 - heartbeatClient.sendMsg(new CustomProtocol(sendMsgReqVO.getUserId(),sendMsgReqVO.getMsg())) ;  
60 -  
61 - // 利用 actuator 来自增  
62 - counterService.increment(Constants.COUNTER_CLIENT_PUSH_COUNT);  
63 -  
64 - SendMsgResVO sendMsgResVO = new SendMsgResVO() ;  
65 - sendMsgResVO.setMsg("OK") ;  
66 - res.setCode(StatusEnum.SUCCESS.getCode()) ;  
67 - res.setMessage(StatusEnum.SUCCESS.getMessage()) ;  
68 - res.setDataBody(sendMsgResVO) ;  
69 - return res ;  
70 - }  
71 48
72 /** 49 /**
73 * 向服务端发消息 字符串 50 * 向服务端发消息 字符串
1 -package com.crossoverjie.cim.client.encode;  
2 -  
3 -import com.crossoverjie.cim.common.pojo.CustomProtocol;  
4 -import io.netty.buffer.ByteBuf;  
5 -import io.netty.channel.ChannelHandlerContext;  
6 -import io.netty.handler.codec.MessageToByteEncoder;  
7 -  
8 -/**  
9 - * Function:编码  
10 - *  
11 - * @author crossoverJie  
12 - * Date: 17/05/2018 19:07  
13 - * @since JDK 1.8  
14 - */  
15 -public class HeartbeatEncode extends MessageToByteEncoder<CustomProtocol> {  
16 - @Override  
17 - protected void encode(ChannelHandlerContext ctx, CustomProtocol msg, ByteBuf out) throws Exception {  
18 -  
19 - out.writeLong(msg.getId()) ;  
20 - out.writeBytes(msg.getContent().getBytes()) ;  
21 -  
22 - }  
23 -}  
@@ -33,7 +33,7 @@ public class CIMClientHandle extends SimpleChannelInboundHandler<CIMResponseProt @@ -33,7 +33,7 @@ public class CIMClientHandle extends SimpleChannelInboundHandler<CIMResponseProt
33 IdleStateEvent idleStateEvent = (IdleStateEvent) evt ; 33 IdleStateEvent idleStateEvent = (IdleStateEvent) evt ;
34 34
35 if (idleStateEvent.state() == IdleState.WRITER_IDLE){ 35 if (idleStateEvent.state() == IdleState.WRITER_IDLE){
36 - LOGGER.info("已经 10 秒没有发送信息!"); 36 + //LOGGER.info("已经 10 秒没有发送信息!");
37 //向服务端发送消息 37 //向服务端发送消息
38 CIMRequestProto.CIMReqProtocol heartBeat = SpringBeanFactory.getBean("heartBeat", CIMRequestProto.CIMReqProtocol.class); 38 CIMRequestProto.CIMReqProtocol heartBeat = SpringBeanFactory.getBean("heartBeat", CIMRequestProto.CIMReqProtocol.class);
39 ctx.writeAndFlush(heartBeat) ; 39 ctx.writeAndFlush(heartBeat) ;
@@ -58,7 +58,7 @@ public class CIMClientHandle extends SimpleChannelInboundHandler<CIMResponseProt @@ -58,7 +58,7 @@ public class CIMClientHandle extends SimpleChannelInboundHandler<CIMResponseProt
58 //从服务端收到消息时被调用 58 //从服务端收到消息时被调用
59 //LOGGER.info("客户端收到消息={}",in.toString(CharsetUtil.UTF_8)) ; 59 //LOGGER.info("客户端收到消息={}",in.toString(CharsetUtil.UTF_8)) ;
60 60
61 - LOGGER.info("客户端收到消息={}" ,responseProtocol.getResMsg()); 61 + LOGGER.info(responseProtocol.getResMsg());
62 } 62 }
63 63
64 @Override 64 @Override
@@ -24,8 +24,8 @@ public class CIMClientHandleInitializer extends ChannelInitializer<Channel> { @@ -24,8 +24,8 @@ public class CIMClientHandleInitializer extends ChannelInitializer<Channel> {
24 @Override 24 @Override
25 protected void initChannel(Channel ch) throws Exception { 25 protected void initChannel(Channel ch) throws Exception {
26 ch.pipeline() 26 ch.pipeline()
27 - //10 秒没发送消息 将IdleStateHandler 添加到 ChannelPipeline 中  
28 - .addLast(new IdleStateHandler(0, 10, 0)) 27 + //60 秒没发送消息 将IdleStateHandler 添加到 ChannelPipeline 中
  28 + .addLast(new IdleStateHandler(0, 60, 0))
29 29
30 //心跳解码 30 //心跳解码
31 //.addLast(new HeartbeatEncode()) 31 //.addLast(new HeartbeatEncode())
1 package com.crossoverjie.cim.client.scanner; 1 package com.crossoverjie.cim.client.scanner;
2 2
3 import com.crossoverjie.cim.client.client.CIMClient; 3 import com.crossoverjie.cim.client.client.CIMClient;
  4 +import com.crossoverjie.cim.client.config.AppConfiguration;
4 import com.crossoverjie.cim.client.service.RouteRequest; 5 import com.crossoverjie.cim.client.service.RouteRequest;
5 import com.crossoverjie.cim.client.util.SpringBeanFactory; 6 import com.crossoverjie.cim.client.util.SpringBeanFactory;
6 import com.crossoverjie.cim.client.vo.req.GoogleProtocolVO; 7 import com.crossoverjie.cim.client.vo.req.GoogleProtocolVO;
@@ -25,10 +26,10 @@ public class Scan implements Runnable { @@ -25,10 +26,10 @@ public class Scan implements Runnable {
25 26
26 private RouteRequest routeRequest; 27 private RouteRequest routeRequest;
27 28
28 - private Long userId ; 29 + private AppConfiguration configuration;
29 30
30 - public Scan(Long userId) {  
31 - this.userId = userId ; 31 + public Scan() {
  32 + this.configuration = SpringBeanFactory.getBean(AppConfiguration.class);
32 this.heartbeatClient = SpringBeanFactory.getBean(CIMClient.class); 33 this.heartbeatClient = SpringBeanFactory.getBean(CIMClient.class);
33 this.routeRequest = SpringBeanFactory.getBean(RouteRequest.class); 34 this.routeRequest = SpringBeanFactory.getBean(RouteRequest.class);
34 } 35 }
@@ -42,7 +43,7 @@ public class Scan implements Runnable { @@ -42,7 +43,7 @@ public class Scan implements Runnable {
42 String msg = sc.nextLine(); 43 String msg = sc.nextLine();
43 44
44 //单聊 45 //单聊
45 - totalMsg = msg.split(" "); 46 + totalMsg = msg.split("><");
46 if (totalMsg.length > 1) { 47 if (totalMsg.length > 1) {
47 vo = new GoogleProtocolVO(); 48 vo = new GoogleProtocolVO();
48 vo.setRequestId(Integer.parseInt(totalMsg[0])); 49 vo.setRequestId(Integer.parseInt(totalMsg[0]));
@@ -51,15 +52,15 @@ public class Scan implements Runnable { @@ -51,15 +52,15 @@ public class Scan implements Runnable {
51 } else { 52 } else {
52 //群聊 53 //群聊
53 try { 54 try {
54 - GroupReqVO groupReqVO = new GroupReqVO(userId,msg) ;  
55 - routeRequest.sendGroupMsg(groupReqVO) ; 55 + GroupReqVO groupReqVO = new GroupReqVO(configuration.getUserId(), msg);
  56 + routeRequest.sendGroupMsg(groupReqVO);
56 } catch (Exception e) { 57 } catch (Exception e) {
57 LOGGER.error("Exception", e); 58 LOGGER.error("Exception", e);
58 } 59 }
59 } 60 }
60 61
61 62
62 - LOGGER.info("scan =[{}]", msg); 63 + LOGGER.info("{}:【{}】", configuration.getUserName(), msg);
63 } 64 }
64 } 65 }
65 } 66 }
1 -package com.crossoverjie.cim.server.kit; 1 +package com.crossoverjie.cim.common.pojo;
2 2
3 /** 3 /**
4 * Function: 4 * Function:
1 -package com.crossoverjie.cim.common.pojo;  
2 -  
3 -import java.io.Serializable;  
4 -  
5 -/**  
6 - * Function:  
7 - *  
8 - * @author crossoverJie  
9 - * Date: 17/05/2018 17:50  
10 - * @since JDK 1.8  
11 - */  
12 -public class CustomProtocol implements Serializable{  
13 -  
14 - private static final long serialVersionUID = 4671171056588401542L;  
15 - private long id ;  
16 - private String content ;  
17 -  
18 - public long getId() {  
19 - return id;  
20 - }  
21 -  
22 - public void setId(long id) {  
23 - this.id = id;  
24 - }  
25 -  
26 - public String getContent() {  
27 - return content;  
28 - }  
29 -  
30 - public void setContent(String content) {  
31 - this.content = content;  
32 - }  
33 -  
34 - public CustomProtocol() {  
35 - }  
36 -  
37 - public CustomProtocol(long id, String content) {  
38 - this.id = id;  
39 - this.content = content;  
40 - }  
41 -  
42 - @Override  
43 - public String toString() {  
44 - return "CustomProtocol{" +  
45 - "id=" + id +  
46 - ", content='" + content + '\'' +  
47 - '}';  
48 - }  
49 -}  
1 package com.crossoverjie.cim.route.controller; 1 package com.crossoverjie.cim.route.controller;
2 2
3 import com.crossoverjie.cim.common.enums.StatusEnum; 3 import com.crossoverjie.cim.common.enums.StatusEnum;
  4 +import com.crossoverjie.cim.common.pojo.CIMUserInfo;
4 import com.crossoverjie.cim.common.res.BaseResponse; 5 import com.crossoverjie.cim.common.res.BaseResponse;
5 import com.crossoverjie.cim.common.res.NULLBody; 6 import com.crossoverjie.cim.common.res.NULLBody;
6 import com.crossoverjie.cim.route.cache.ServerCache; 7 import com.crossoverjie.cim.route.cache.ServerCache;
7 import com.crossoverjie.cim.route.service.AccountService; 8 import com.crossoverjie.cim.route.service.AccountService;
  9 +import com.crossoverjie.cim.route.service.UserInfoCacheService;
8 import com.crossoverjie.cim.route.vo.req.ChatReqVO; 10 import com.crossoverjie.cim.route.vo.req.ChatReqVO;
9 import com.crossoverjie.cim.route.vo.req.LoginReqVO; 11 import com.crossoverjie.cim.route.vo.req.LoginReqVO;
10 import com.crossoverjie.cim.route.vo.req.P2PReqVO; 12 import com.crossoverjie.cim.route.vo.req.P2PReqVO;
@@ -41,6 +43,9 @@ public class RouteController { @@ -41,6 +43,9 @@ public class RouteController {
41 @Autowired 43 @Autowired
42 private AccountService accountService; 44 private AccountService accountService;
43 45
  46 + @Autowired
  47 + private UserInfoCacheService userInfoCacheService ;
  48 +
44 @ApiOperation("群聊 API") 49 @ApiOperation("群聊 API")
45 @RequestMapping(value = "groupRoute", method = RequestMethod.POST) 50 @RequestMapping(value = "groupRoute", method = RequestMethod.POST)
46 @ResponseBody() 51 @ResponseBody()
@@ -56,7 +61,8 @@ public class RouteController { @@ -56,7 +61,8 @@ public class RouteController {
56 CIMServerResVO value = cimServerResVOEntry.getValue(); 61 CIMServerResVO value = cimServerResVOEntry.getValue();
57 if (userId.equals(groupReqVO.getUserId())){ 62 if (userId.equals(groupReqVO.getUserId())){
58 //过滤掉自己 63 //过滤掉自己
59 - LOGGER.info("过滤掉了发送者 userId={}",groupReqVO.getUserId()); 64 + CIMUserInfo cimUserInfo = userInfoCacheService.loadUserInfo(groupReqVO.getUserId());
  65 + LOGGER.warn("过滤掉了发送者 userId={}",cimUserInfo.toString());
60 continue; 66 continue;
61 } 67 }
62 68
@@ -79,7 +85,9 @@ public class RouteController { @@ -79,7 +85,9 @@ public class RouteController {
79 public BaseResponse<NULLBody> offLine(@RequestBody ChatReqVO groupReqVO) throws Exception { 85 public BaseResponse<NULLBody> offLine(@RequestBody ChatReqVO groupReqVO) throws Exception {
80 BaseResponse<NULLBody> res = new BaseResponse(); 86 BaseResponse<NULLBody> res = new BaseResponse();
81 87
82 - LOGGER.info("下线用户[{}]", groupReqVO.toString()); 88 + CIMUserInfo cimUserInfo = userInfoCacheService.loadUserInfo(groupReqVO.getUserId());
  89 +
  90 + LOGGER.info("下线用户[{}]", cimUserInfo.toString());
83 accountService.offLine(groupReqVO.getUserId()); 91 accountService.offLine(groupReqVO.getUserId());
84 92
85 res.setCode(StatusEnum.SUCCESS.getCode()); 93 res.setCode(StatusEnum.SUCCESS.getCode());
  1 +package com.crossoverjie.cim.route.service;
  2 +
  3 +import com.crossoverjie.cim.common.pojo.CIMUserInfo;
  4 +
  5 +/**
  6 + * Function:
  7 + *
  8 + * @author crossoverJie
  9 + * Date: 2018/12/24 11:06
  10 + * @since JDK 1.8
  11 + */
  12 +public interface UserInfoCacheService {
  13 +
  14 + /**
  15 + * 通过 userID 获取用户信息
  16 + * @param userId
  17 + * @return
  18 + * @throws Exception
  19 + */
  20 + CIMUserInfo loadUserInfo(long userId) throws Exception ;
  21 +}
1 package com.crossoverjie.cim.route.service.impl; 1 package com.crossoverjie.cim.route.service.impl;
2 2
3 import com.alibaba.fastjson.JSONObject; 3 import com.alibaba.fastjson.JSONObject;
  4 +import com.crossoverjie.cim.common.pojo.CIMUserInfo;
4 import com.crossoverjie.cim.route.service.AccountService; 5 import com.crossoverjie.cim.route.service.AccountService;
  6 +import com.crossoverjie.cim.route.service.UserInfoCacheService;
5 import com.crossoverjie.cim.route.vo.req.ChatReqVO; 7 import com.crossoverjie.cim.route.vo.req.ChatReqVO;
6 import com.crossoverjie.cim.route.vo.req.LoginReqVO; 8 import com.crossoverjie.cim.route.vo.req.LoginReqVO;
7 import com.crossoverjie.cim.route.vo.res.CIMServerResVO; 9 import com.crossoverjie.cim.route.vo.res.CIMServerResVO;
@@ -39,6 +41,9 @@ public class AccountServiceRedisImpl implements AccountService { @@ -39,6 +41,9 @@ public class AccountServiceRedisImpl implements AccountService {
39 private RedisTemplate<String, String> redisTemplate; 41 private RedisTemplate<String, String> redisTemplate;
40 42
41 @Autowired 43 @Autowired
  44 + private UserInfoCacheService userInfoCacheService ;
  45 +
  46 + @Autowired
42 private OkHttpClient okHttpClient; 47 private OkHttpClient okHttpClient;
43 48
44 private MediaType mediaType = MediaType.parse("application/json"); 49 private MediaType mediaType = MediaType.parse("application/json");
@@ -114,11 +119,10 @@ public class AccountServiceRedisImpl implements AccountService { @@ -114,11 +119,10 @@ public class AccountServiceRedisImpl implements AccountService {
114 119
115 @Override 120 @Override
116 public void pushMsg(String url, long sendUserId, ChatReqVO groupReqVO) throws Exception { 121 public void pushMsg(String url, long sendUserId, ChatReqVO groupReqVO) throws Exception {
117 - //可考虑本地缓存  
118 - String sendUserName = redisTemplate.opsForValue().get(ACCOUNT_PREFIX + sendUserId); 122 + CIMUserInfo cimUserInfo = userInfoCacheService.loadUserInfo(sendUserId);
119 123
120 JSONObject jsonObject = new JSONObject(); 124 JSONObject jsonObject = new JSONObject();
121 - jsonObject.put("msg", sendUserName + ":【" + groupReqVO.getMsg() + "】"); 125 + jsonObject.put("msg", cimUserInfo.getUserName() + ":【" + groupReqVO.getMsg() + "】");
122 jsonObject.put("userId", groupReqVO.getUserId()); 126 jsonObject.put("userId", groupReqVO.getUserId());
123 RequestBody requestBody = RequestBody.create(mediaType, jsonObject.toString()); 127 RequestBody requestBody = RequestBody.create(mediaType, jsonObject.toString());
124 128
  1 +package com.crossoverjie.cim.route.service.impl;
  2 +
  3 +import com.crossoverjie.cim.common.pojo.CIMUserInfo;
  4 +import com.crossoverjie.cim.route.service.UserInfoCacheService;
  5 +import org.springframework.beans.factory.annotation.Autowired;
  6 +import org.springframework.data.redis.core.RedisTemplate;
  7 +import org.springframework.stereotype.Service;
  8 +
  9 +import java.util.Map;
  10 +import java.util.concurrent.ConcurrentHashMap;
  11 +
  12 +import static com.crossoverjie.cim.route.constant.Constant.ACCOUNT_PREFIX;
  13 +
  14 +/**
  15 + * Function:
  16 + *
  17 + * @author crossoverJie
  18 + * Date: 2018/12/24 11:06
  19 + * @since JDK 1.8
  20 + */
  21 +@Service
  22 +public class UserInfoCacheServiceImpl implements UserInfoCacheService {
  23 +
  24 + /**
  25 + * 本地缓存,后期可换为 LRU
  26 + */
  27 + private final static Map<Long,CIMUserInfo> USER_INFO_MAP = new ConcurrentHashMap<>(64) ;
  28 +
  29 + @Autowired
  30 + private RedisTemplate<String,String> redisTemplate ;
  31 +
  32 + @Override
  33 + public CIMUserInfo loadUserInfo(long userId) throws Exception {
  34 +
  35 + //优先从本地缓存获取
  36 + CIMUserInfo cimUserInfo = USER_INFO_MAP.get(userId);
  37 + if (cimUserInfo != null){
  38 + return cimUserInfo ;
  39 + }
  40 +
  41 + //load redis
  42 + String sendUserName = redisTemplate.opsForValue().get(ACCOUNT_PREFIX + userId);
  43 + if (sendUserName != null){
  44 + cimUserInfo = new CIMUserInfo(userId,sendUserName) ;
  45 + USER_INFO_MAP.put(userId,cimUserInfo) ;
  46 + }
  47 +
  48 + return cimUserInfo;
  49 + }
  50 +}
@@ -13,7 +13,7 @@ logging.level.root=info @@ -13,7 +13,7 @@ logging.level.root=info
13 management.security.enabled=false 13 management.security.enabled=false
14 14
15 # zk 地址 15 # zk 地址
16 -app.zk.addr=47.98.194.60:2181 16 +app.zk.addr=47.98.194.60:2182
17 17
18 # zk 注册根节点 18 # zk 注册根节点
19 app.zk.root=/route 19 app.zk.root=/route
1 -package com.crossoverjie.cim.server.decoder;  
2 -  
3 -import com.crossoverjie.cim.common.pojo.CustomProtocol;  
4 -import io.netty.buffer.ByteBuf;  
5 -import io.netty.channel.ChannelHandlerContext;  
6 -import io.netty.handler.codec.ByteToMessageDecoder;  
7 -  
8 -import java.util.List;  
9 -  
10 -/**  
11 - * Function: 解码信息  
12 - *  
13 - * @author crossoverJie  
14 - * Date: 17/05/2018 18:34  
15 - * @since JDK 1.8  
16 - */  
17 -public class HeartbeatDecoder extends ByteToMessageDecoder {  
18 - @Override  
19 - protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {  
20 -  
21 - long id = in.readLong() ;  
22 - byte[] bytes = new byte[in.readableBytes()] ;  
23 - in.readBytes(bytes) ;  
24 - String content = new String(bytes) ;  
25 -  
26 - CustomProtocol customProtocol = new CustomProtocol() ;  
27 - customProtocol.setId(id);  
28 - customProtocol.setContent(content) ;  
29 - out.add(customProtocol) ;  
30 -  
31 - }  
32 -}  
@@ -2,9 +2,9 @@ package com.crossoverjie.cim.server.handle; @@ -2,9 +2,9 @@ package com.crossoverjie.cim.server.handle;
2 2
3 import com.alibaba.fastjson.JSONObject; 3 import com.alibaba.fastjson.JSONObject;
4 import com.crossoverjie.cim.common.constant.Constants; 4 import com.crossoverjie.cim.common.constant.Constants;
  5 +import com.crossoverjie.cim.common.pojo.CIMUserInfo;
5 import com.crossoverjie.cim.common.protocol.CIMRequestProto; 6 import com.crossoverjie.cim.common.protocol.CIMRequestProto;
6 import com.crossoverjie.cim.server.config.AppConfiguration; 7 import com.crossoverjie.cim.server.config.AppConfiguration;
7 -import com.crossoverjie.cim.server.kit.CIMUserInfo;  
8 import com.crossoverjie.cim.server.util.SessionSocketHolder; 8 import com.crossoverjie.cim.server.util.SessionSocketHolder;
9 import com.crossoverjie.cim.server.util.SpringBeanFactory; 9 import com.crossoverjie.cim.server.util.SpringBeanFactory;
10 import io.netty.channel.ChannelHandler; 10 import io.netty.channel.ChannelHandler;
@@ -63,9 +63,14 @@ public class CIMServerHandle extends SimpleChannelInboundHandler<CIMRequestProto @@ -63,9 +63,14 @@ public class CIMServerHandle extends SimpleChannelInboundHandler<CIMRequestProto
63 .post(requestBody) 63 .post(requestBody)
64 .build(); 64 .build();
65 65
66 - Response response = okHttpClient.newCall(request).execute();  
67 - if (!response.isSuccessful()) {  
68 - throw new IOException("Unexpected code " + response); 66 + Response response = null;
  67 + try {
  68 + response = okHttpClient.newCall(request).execute();
  69 + if (!response.isSuccessful()) {
  70 + throw new IOException("Unexpected code " + response);
  71 + }
  72 + }finally {
  73 + response.body().close();
69 } 74 }
70 } 75 }
71 76
@@ -78,7 +83,7 @@ public class CIMServerHandle extends SimpleChannelInboundHandler<CIMRequestProto @@ -78,7 +83,7 @@ public class CIMServerHandle extends SimpleChannelInboundHandler<CIMRequestProto
78 //保存客户端与 Channel 之间的关系 83 //保存客户端与 Channel 之间的关系
79 SessionSocketHolder.put(msg.getRequestId(),(NioSocketChannel)ctx.channel()) ; 84 SessionSocketHolder.put(msg.getRequestId(),(NioSocketChannel)ctx.channel()) ;
80 SessionSocketHolder.saveSession(msg.getRequestId(),msg.getReqMsg()); 85 SessionSocketHolder.saveSession(msg.getRequestId(),msg.getReqMsg());
81 - LOGGER.info("客户端[{}]注册成功",msg.getReqMsg()); 86 + LOGGER.info("客户端[{}]上线成功",msg.getReqMsg());
82 } 87 }
83 88
84 } 89 }
1 package com.crossoverjie.cim.server.server; 1 package com.crossoverjie.cim.server.server;
2 2
3 -import com.alibaba.fastjson.JSON;  
4 import com.crossoverjie.cim.common.constant.Constants; 3 import com.crossoverjie.cim.common.constant.Constants;
5 -import com.crossoverjie.cim.common.pojo.CustomProtocol;  
6 import com.crossoverjie.cim.common.protocol.CIMRequestProto; 4 import com.crossoverjie.cim.common.protocol.CIMRequestProto;
7 import com.crossoverjie.cim.server.init.CIMServerInitializer; 5 import com.crossoverjie.cim.server.init.CIMServerInitializer;
8 import com.crossoverjie.cim.server.util.SessionSocketHolder; 6 import com.crossoverjie.cim.server.util.SessionSocketHolder;
9 import com.crossoverjie.cim.server.vo.req.SendMsgReqVO; 7 import com.crossoverjie.cim.server.vo.req.SendMsgReqVO;
10 import io.netty.bootstrap.ServerBootstrap; 8 import io.netty.bootstrap.ServerBootstrap;
11 -import io.netty.buffer.Unpooled;  
12 import io.netty.channel.ChannelFuture; 9 import io.netty.channel.ChannelFuture;
13 import io.netty.channel.ChannelFutureListener; 10 import io.netty.channel.ChannelFutureListener;
14 import io.netty.channel.ChannelOption; 11 import io.netty.channel.ChannelOption;
@@ -16,7 +13,6 @@ import io.netty.channel.EventLoopGroup; @@ -16,7 +13,6 @@ import io.netty.channel.EventLoopGroup;
16 import io.netty.channel.nio.NioEventLoopGroup; 13 import io.netty.channel.nio.NioEventLoopGroup;
17 import io.netty.channel.socket.nio.NioServerSocketChannel; 14 import io.netty.channel.socket.nio.NioServerSocketChannel;
18 import io.netty.channel.socket.nio.NioSocketChannel; 15 import io.netty.channel.socket.nio.NioSocketChannel;
19 -import io.netty.util.CharsetUtil;  
20 import org.slf4j.Logger; 16 import org.slf4j.Logger;
21 import org.slf4j.LoggerFactory; 17 import org.slf4j.LoggerFactory;
22 import org.springframework.beans.factory.annotation.Value; 18 import org.springframework.beans.factory.annotation.Value;
@@ -82,23 +78,6 @@ public class CIMServer { @@ -82,23 +78,6 @@ public class CIMServer {
82 78
83 79
84 /** 80 /**
85 - * 发送消息  
86 - *  
87 - * @param customProtocol  
88 - */  
89 - public void sendMsg(CustomProtocol customProtocol) {  
90 - NioSocketChannel socketChannel = SessionSocketHolder.get(customProtocol.getId());  
91 -  
92 - if (null == socketChannel) {  
93 - throw new NullPointerException("没有[" + customProtocol.getId() + "]的socketChannel");  
94 - }  
95 -  
96 - ChannelFuture future = socketChannel.writeAndFlush(Unpooled.copiedBuffer(customProtocol.toString(), CharsetUtil.UTF_8));  
97 - future.addListener((ChannelFutureListener) channelFuture ->  
98 - LOGGER.info("服务端手动发消息成功={}", JSON.toJSONString(customProtocol)));  
99 - }  
100 -  
101 - /**  
102 * 发送 Google Protocol 编码消息 81 * 发送 Google Protocol 编码消息
103 * @param sendMsgReqVO 消息 82 * @param sendMsgReqVO 消息
104 */ 83 */
1 package com.crossoverjie.cim.server.util; 1 package com.crossoverjie.cim.server.util;
2 2
3 -import com.crossoverjie.cim.server.kit.CIMUserInfo; 3 +import com.crossoverjie.cim.common.pojo.CIMUserInfo;
4 import io.netty.channel.socket.nio.NioSocketChannel; 4 import io.netty.channel.socket.nio.NioSocketChannel;
5 5
6 import java.util.Map; 6 import java.util.Map;
@@ -25,7 +25,7 @@ monitor.channel.map.key=channelMap @@ -25,7 +25,7 @@ monitor.channel.map.key=channelMap
25 app.zk.switch=true 25 app.zk.switch=true
26 26
27 # zk 地址 27 # zk 地址
28 -app.zk.addr=47.98.194.60:2181 28 +app.zk.addr=47.98.194.60:2182
29 29
30 # zk 注册根节点 30 # zk 注册根节点
31 app.zk.root=/route 31 app.zk.root=/route
@@ -38,6 +38,6 @@ public class Application implements CommandLineRunner{ @@ -38,6 +38,6 @@ public class Application implements CommandLineRunner{
38 String addr = InetAddress.getLocalHost().getHostAddress(); 38 String addr = InetAddress.getLocalHost().getHostAddress();
39 Thread thread = new Thread(new RegistryZK(addr, appConfiguration.getPort())); 39 Thread thread = new Thread(new RegistryZK(addr, appConfiguration.getPort()));
40 thread.setName("registry-zk"); 40 thread.setName("registry-zk");
41 - thread.start() ; 41 + //thread.start() ;
42 } 42 }
43 } 43 }
1 spring.application.name=cim-zk 1 spring.application.name=cim-zk
2 2
3 -# web cimServerPort  
4 -server.cimServerPort=8083 3 +# web port
  4 +server.port=9083
5 5
6 # 是否打开swagger 6 # 是否打开swagger
7 swagger.enable = true 7 swagger.enable = true