作者 crossoverJie
提交者 GitHub

cim 1.0.5 (#51)

cim 1.0.5
正在显示 38 个修改的文件 包含 404 行增加789 行删除
@@ -87,6 +87,12 @@ @@ -87,6 +87,12 @@
87 <artifactId>guava</artifactId> 87 <artifactId>guava</artifactId>
88 </dependency> 88 </dependency>
89 89
  90 + <dependency>
  91 + <groupId>com.vdurmont</groupId>
  92 + <artifactId>emoji-java</artifactId>
  93 + <version>5.0.0</version>
  94 + </dependency>
  95 +
90 </dependencies> 96 </dependencies>
91 97
92 <build> 98 <build>
@@ -2,6 +2,7 @@ package com.crossoverjie.cim.client.client; @@ -2,6 +2,7 @@ package com.crossoverjie.cim.client.client;
2 2
3 import com.crossoverjie.cim.client.config.AppConfiguration; 3 import com.crossoverjie.cim.client.config.AppConfiguration;
4 import com.crossoverjie.cim.client.init.CIMClientHandleInitializer; 4 import com.crossoverjie.cim.client.init.CIMClientHandleInitializer;
  5 +import com.crossoverjie.cim.client.service.EchoService;
5 import com.crossoverjie.cim.client.service.MsgHandle; 6 import com.crossoverjie.cim.client.service.MsgHandle;
6 import com.crossoverjie.cim.client.service.RouteRequest; 7 import com.crossoverjie.cim.client.service.RouteRequest;
7 import com.crossoverjie.cim.client.service.impl.ClientInfo; 8 import com.crossoverjie.cim.client.service.impl.ClientInfo;
@@ -51,6 +52,9 @@ public class CIMClient { @@ -51,6 +52,9 @@ public class CIMClient {
51 private SocketChannel channel; 52 private SocketChannel channel;
52 53
53 @Autowired 54 @Autowired
  55 + private EchoService echoService ;
  56 +
  57 + @Autowired
54 private RouteRequest routeRequest; 58 private RouteRequest routeRequest;
55 59
56 @Autowired 60 @Autowired
@@ -102,12 +106,13 @@ public class CIMClient { @@ -102,12 +106,13 @@ public class CIMClient {
102 errorCount++; 106 errorCount++;
103 107
104 if (errorCount >= configuration.getErrorCount()) { 108 if (errorCount >= configuration.getErrorCount()) {
105 - LOGGER.error("接失败次数达到上限[{}]次", errorCount); 109 + LOGGER.error("接失败次数达到上限[{}]次", errorCount);
106 msgHandle.shutdown(); 110 msgHandle.shutdown();
107 } 111 }
108 LOGGER.error("连接失败", e); 112 LOGGER.error("连接失败", e);
109 } 113 }
110 if (future.isSuccess()) { 114 if (future.isSuccess()) {
  115 + echoService.echo("start cim client success!");
111 LOGGER.info("启动 cim client 成功"); 116 LOGGER.info("启动 cim client 成功");
112 } 117 }
113 channel = (SocketChannel) future.channel(); 118 channel = (SocketChannel) future.channel();
@@ -137,7 +142,7 @@ public class CIMClient { @@ -137,7 +142,7 @@ public class CIMClient {
137 LOGGER.error("重连次数达到上限[{}]次", errorCount); 142 LOGGER.error("重连次数达到上限[{}]次", errorCount);
138 msgHandle.shutdown(); 143 msgHandle.shutdown();
139 } 144 }
140 - LOGGER.error("登录失败", e); 145 + LOGGER.error("login fail", e);
141 } 146 }
142 return cimServer; 147 return cimServer;
143 } 148 }
@@ -153,7 +158,8 @@ public class CIMClient { @@ -153,7 +158,8 @@ public class CIMClient {
153 .build(); 158 .build();
154 ChannelFuture future = channel.writeAndFlush(login); 159 ChannelFuture future = channel.writeAndFlush(login);
155 future.addListener((ChannelFutureListener) channelFuture -> 160 future.addListener((ChannelFutureListener) channelFuture ->
156 - LOGGER.info("注册成功={}", login.toString())); 161 + echoService.echo("registry cim server success!")
  162 + );
157 } 163 }
158 164
159 /** 165 /**
@@ -198,9 +204,9 @@ public class CIMClient { @@ -198,9 +204,9 @@ public class CIMClient {
198 //首先清除路由信息,下线 204 //首先清除路由信息,下线
199 routeRequest.offLine(); 205 routeRequest.offLine();
200 206
201 - LOGGER.info("开始重连。。"); 207 + LOGGER.info("reconnect....");
202 start(); 208 start();
203 - LOGGER.info("重连成功!!"); 209 + LOGGER.info("reconnect success");
204 } 210 }
205 211
206 /** 212 /**
  1 +package com.crossoverjie.cim.client.constant;
  2 +
  3 +/**
  4 + * Function:
  5 + *
  6 + * @author crossoverJie
  7 + * Date: 2019-08-24 22:53
  8 + * @since JDK 1.8
  9 + */
  10 +public class Emoji {
  11 +
  12 +}
@@ -7,6 +7,7 @@ import com.crossoverjie.cim.common.constant.Constants; @@ -7,6 +7,7 @@ import com.crossoverjie.cim.common.constant.Constants;
7 import com.crossoverjie.cim.common.protocol.CIMRequestProto; 7 import com.crossoverjie.cim.common.protocol.CIMRequestProto;
8 import com.crossoverjie.cim.common.protocol.CIMResponseProto; 8 import com.crossoverjie.cim.common.protocol.CIMResponseProto;
9 import com.crossoverjie.cim.common.util.NettyAttrUtil; 9 import com.crossoverjie.cim.common.util.NettyAttrUtil;
  10 +import com.vdurmont.emoji.EmojiParser;
10 import io.netty.channel.ChannelFutureListener; 11 import io.netty.channel.ChannelFutureListener;
11 import io.netty.channel.ChannelHandler; 12 import io.netty.channel.ChannelHandler;
12 import io.netty.channel.ChannelHandlerContext; 13 import io.netty.channel.ChannelHandlerContext;
@@ -105,7 +106,9 @@ public class CIMClientHandle extends SimpleChannelInboundHandler<CIMResponseProt @@ -105,7 +106,9 @@ public class CIMClientHandle extends SimpleChannelInboundHandler<CIMResponseProt
105 //回调消息 106 //回调消息
106 callBackMsg(msg.getResMsg()); 107 callBackMsg(msg.getResMsg());
107 108
108 - LOGGER.info(msg.getResMsg()); 109 + //将消息中的 emoji 表情格式化为 Unicode 编码以便在终端可以显示
  110 + String response = EmojiParser.parseToUnicode(msg.getResMsg());
  111 + System.out.println(response);
109 } 112 }
110 113
111 114
1 package com.crossoverjie.cim.client.scanner; 1 package com.crossoverjie.cim.client.scanner;
2 2
3 import com.crossoverjie.cim.client.config.AppConfiguration; 3 import com.crossoverjie.cim.client.config.AppConfiguration;
  4 +import com.crossoverjie.cim.client.service.EchoService;
4 import com.crossoverjie.cim.client.service.MsgHandle; 5 import com.crossoverjie.cim.client.service.MsgHandle;
5 import com.crossoverjie.cim.client.service.MsgLogger; 6 import com.crossoverjie.cim.client.service.MsgLogger;
6 import com.crossoverjie.cim.client.util.SpringBeanFactory; 7 import com.crossoverjie.cim.client.util.SpringBeanFactory;
  8 +import com.vdurmont.emoji.EmojiParser;
7 import org.slf4j.Logger; 9 import org.slf4j.Logger;
8 import org.slf4j.LoggerFactory; 10 import org.slf4j.LoggerFactory;
9 11
@@ -29,10 +31,13 @@ public class Scan implements Runnable { @@ -29,10 +31,13 @@ public class Scan implements Runnable {
29 31
30 private MsgLogger msgLogger ; 32 private MsgLogger msgLogger ;
31 33
  34 + private EchoService echoService ;
  35 +
32 public Scan() { 36 public Scan() {
33 this.configuration = SpringBeanFactory.getBean(AppConfiguration.class); 37 this.configuration = SpringBeanFactory.getBean(AppConfiguration.class);
34 this.msgHandle = SpringBeanFactory.getBean(MsgHandle.class) ; 38 this.msgHandle = SpringBeanFactory.getBean(MsgHandle.class) ;
35 this.msgLogger = SpringBeanFactory.getBean(MsgLogger.class) ; 39 this.msgLogger = SpringBeanFactory.getBean(MsgLogger.class) ;
  40 + this.echoService = SpringBeanFactory.getBean(EchoService.class) ;
36 } 41 }
37 42
38 @Override 43 @Override
@@ -57,7 +62,7 @@ public class Scan implements Runnable { @@ -57,7 +62,7 @@ public class Scan implements Runnable {
57 //写入聊天记录 62 //写入聊天记录
58 msgLogger.log(msg) ; 63 msgLogger.log(msg) ;
59 64
60 - LOGGER.info("{}:【{}】", configuration.getUserName(), msg); 65 + echoService.echo(EmojiParser.parseToUnicode(msg));
61 } 66 }
62 } 67 }
63 68
  1 +package com.crossoverjie.cim.client.service;
  2 +
  3 +/**
  4 + * Function:
  5 + *
  6 + * @author crossoverJie
  7 + * Date: 2019-08-27 22:35
  8 + * @since JDK 1.8
  9 + */
  10 +public interface EchoService {
  11 +
  12 + /**
  13 + * echo msg to terminal
  14 + * @param msg message
  15 + * @param replace
  16 + */
  17 + void echo(String msg, Object... replace) ;
  18 +}
@@ -38,7 +38,7 @@ public class ClientInfo { @@ -38,7 +38,7 @@ public class ClientInfo {
38 return this; 38 return this;
39 } 39 }
40 40
41 - private class Info{ 41 + public class Info{
42 private String userName; 42 private String userName;
43 private long userId ; 43 private long userId ;
44 private String serviceInfo ; 44 private String serviceInfo ;
  1 +package com.crossoverjie.cim.client.service.impl;
  2 +
  3 +import com.crossoverjie.cim.client.config.AppConfiguration;
  4 +import com.crossoverjie.cim.client.service.EchoService;
  5 +import org.springframework.beans.factory.annotation.Autowired;
  6 +import org.springframework.stereotype.Service;
  7 +
  8 +/**
  9 + * Function:
  10 + *
  11 + * @author crossoverJie
  12 + * Date: 2019-08-27 22:37
  13 + * @since JDK 1.8
  14 + */
  15 +@Service
  16 +public class EchoServiceImpl implements EchoService {
  17 +
  18 + private static final String PREFIX = "$";
  19 +
  20 + @Autowired
  21 + private AppConfiguration appConfiguration;
  22 +
  23 + @Override
  24 + public void echo(String msg,Object... replace) {
  25 + msg = "\033[31;4m" + appConfiguration.getUserName() + PREFIX + "\033[0m" + " " + msg;
  26 +
  27 + String log = print(msg, replace);
  28 +
  29 + System.out.println(log);
  30 + }
  31 +
  32 +
  33 + /**
  34 + * print msg
  35 + * @param msg
  36 + * @param place
  37 + * @return
  38 + */
  39 + private String print(String msg, Object... place) {
  40 + StringBuilder sb = new StringBuilder();
  41 + int k = 0;
  42 + for (int i = 0; i < place.length; i++) {
  43 + int index = msg.indexOf("{}", k);
  44 +
  45 + if (index == -1){
  46 + return msg;
  47 + }
  48 +
  49 + if (index != 0) {
  50 + sb.append(msg, k, index);
  51 + sb.append(place[i]);
  52 +
  53 + if (place.length == 1) {
  54 + sb.append(msg, index + 2, msg.length());
  55 + }
  56 +
  57 + } else {
  58 + sb.append(place[i]);
  59 + if (place.length == 1) {
  60 + sb.append(msg, index + 2, msg.length());
  61 + }
  62 + }
  63 +
  64 + k = index + 2;
  65 + }
  66 + if (sb.toString().equals("")){
  67 + return msg ;
  68 + }else {
  69 + return sb.toString();
  70 + }
  71 + }
  72 +}
@@ -2,12 +2,13 @@ package com.crossoverjie.cim.client.service.impl; @@ -2,12 +2,13 @@ package com.crossoverjie.cim.client.service.impl;
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.config.AppConfiguration;
5 -import com.crossoverjie.cim.client.service.*; 5 +import com.crossoverjie.cim.client.service.InnerCommand;
  6 +import com.crossoverjie.cim.client.service.InnerCommandContext;
  7 +import com.crossoverjie.cim.client.service.MsgHandle;
  8 +import com.crossoverjie.cim.client.service.MsgLogger;
  9 +import com.crossoverjie.cim.client.service.RouteRequest;
6 import com.crossoverjie.cim.client.vo.req.GroupReqVO; 10 import com.crossoverjie.cim.client.vo.req.GroupReqVO;
7 import com.crossoverjie.cim.client.vo.req.P2PReqVO; 11 import com.crossoverjie.cim.client.vo.req.P2PReqVO;
8 -import com.crossoverjie.cim.client.vo.res.OnlineUsersResVO;  
9 -import com.crossoverjie.cim.common.data.construct.TrieTree;  
10 -import com.crossoverjie.cim.common.enums.SystemCommandEnum;  
11 import com.crossoverjie.cim.common.util.StringUtil; 12 import com.crossoverjie.cim.common.util.StringUtil;
12 import org.slf4j.Logger; 13 import org.slf4j.Logger;
13 import org.slf4j.LoggerFactory; 14 import org.slf4j.LoggerFactory;
@@ -15,8 +16,6 @@ import org.springframework.beans.factory.annotation.Autowired; @@ -15,8 +16,6 @@ import org.springframework.beans.factory.annotation.Autowired;
15 import org.springframework.stereotype.Service; 16 import org.springframework.stereotype.Service;
16 17
17 import javax.annotation.Resource; 18 import javax.annotation.Resource;
18 -import java.util.List;  
19 -import java.util.Map;  
20 import java.util.concurrent.ThreadPoolExecutor; 19 import java.util.concurrent.ThreadPoolExecutor;
21 import java.util.concurrent.TimeUnit; 20 import java.util.concurrent.TimeUnit;
22 21
@@ -144,63 +143,6 @@ public class MsgHandler implements MsgHandle { @@ -144,63 +143,6 @@ public class MsgHandler implements MsgHandle {
144 143
145 } 144 }
146 145
147 -  
148 - /**  
149 - * 模糊匹配  
150 - *  
151 - * @param msg  
152 - */  
153 - private void prefixSearch(String msg) {  
154 - try {  
155 - List<OnlineUsersResVO.DataBodyBean> onlineUsers = routeRequest.onlineUsers();  
156 - TrieTree trieTree = new TrieTree();  
157 - for (OnlineUsersResVO.DataBodyBean onlineUser : onlineUsers) {  
158 - trieTree.insert(onlineUser.getUserName());  
159 - }  
160 -  
161 - String[] split = msg.split(" ");  
162 - String key = split[1];  
163 - List<String> list = trieTree.prefixSearch(key);  
164 -  
165 - for (String res : list) {  
166 - res = res.replace(key, "\033[31;4m" + key + "\033[0m");  
167 - System.out.println(res);  
168 - }  
169 -  
170 - } catch (Exception e) {  
171 - LOGGER.error("Exception", e);  
172 - }  
173 - }  
174 -  
175 - /**  
176 - * 查询聊天记录  
177 - *  
178 - * @param msg  
179 - */  
180 - private void queryChatHistory(String msg) {  
181 - String[] split = msg.split(" ");  
182 - String res = msgLogger.query(split[1]);  
183 - System.out.println(res);  
184 - }  
185 -  
186 - /**  
187 - * 打印在线用户  
188 - */  
189 - private void printOnlineUsers() {  
190 - try {  
191 - List<OnlineUsersResVO.DataBodyBean> onlineUsers = routeRequest.onlineUsers();  
192 -  
193 - LOGGER.info("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");  
194 - for (OnlineUsersResVO.DataBodyBean onlineUser : onlineUsers) {  
195 - LOGGER.info("userId={}=====userName={}", onlineUser.getUserId(), onlineUser.getUserName());  
196 - }  
197 - LOGGER.info("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");  
198 -  
199 - } catch (Exception e) {  
200 - LOGGER.error("Exception", e);  
201 - }  
202 - }  
203 -  
204 /** 146 /**
205 * 关闭系统 147 * 关闭系统
206 */ 148 */
@@ -231,13 +173,4 @@ public class MsgHandler implements MsgHandle { @@ -231,13 +173,4 @@ public class MsgHandler implements MsgHandle {
231 aiModel = false ; 173 aiModel = false ;
232 } 174 }
233 175
234 - private void printAllCommand(Map<String, String> allStatusCode) {  
235 - LOGGER.warn("====================================");  
236 - for (Map.Entry<String, String> stringStringEntry : allStatusCode.entrySet()) {  
237 - String key = stringStringEntry.getKey();  
238 - String value = stringStringEntry.getValue();  
239 - LOGGER.warn(key + "----->" + value);  
240 - }  
241 - LOGGER.warn("====================================");  
242 - }  
243 } 176 }
@@ -3,6 +3,7 @@ package com.crossoverjie.cim.client.service.impl; @@ -3,6 +3,7 @@ package com.crossoverjie.cim.client.service.impl;
3 import com.alibaba.fastjson.JSON; 3 import com.alibaba.fastjson.JSON;
4 import com.alibaba.fastjson.JSONObject; 4 import com.alibaba.fastjson.JSONObject;
5 import com.crossoverjie.cim.client.config.AppConfiguration; 5 import com.crossoverjie.cim.client.config.AppConfiguration;
  6 +import com.crossoverjie.cim.client.service.EchoService;
6 import com.crossoverjie.cim.client.service.RouteRequest; 7 import com.crossoverjie.cim.client.service.RouteRequest;
7 import com.crossoverjie.cim.client.vo.req.GroupReqVO; 8 import com.crossoverjie.cim.client.vo.req.GroupReqVO;
8 import com.crossoverjie.cim.client.vo.req.LoginReqVO; 9 import com.crossoverjie.cim.client.vo.req.LoginReqVO;
@@ -50,6 +51,8 @@ public class RouteRequestImpl implements RouteRequest { @@ -50,6 +51,8 @@ public class RouteRequestImpl implements RouteRequest {
50 @Value("${cim.server.online.user.url}") 51 @Value("${cim.server.online.user.url}")
51 private String onlineUserUrl; 52 private String onlineUserUrl;
52 53
  54 + @Autowired
  55 + private EchoService echoService ;
53 56
54 57
55 @Autowired 58 @Autowired
@@ -136,7 +139,7 @@ public class RouteRequestImpl implements RouteRequest { @@ -136,7 +139,7 @@ public class RouteRequestImpl implements RouteRequest {
136 139
137 //重复失败 140 //重复失败
138 if (!cimServerResVO.getCode().equals(StatusEnum.SUCCESS.getCode())){ 141 if (!cimServerResVO.getCode().equals(StatusEnum.SUCCESS.getCode())){
139 - LOGGER.error(appConfiguration.getUserName() + ":" + cimServerResVO.getMessage()); 142 + echoService.echo(cimServerResVO.getMessage());
140 System.exit(-1); 143 System.exit(-1);
141 } 144 }
142 145
1 package com.crossoverjie.cim.client.service.impl.command; 1 package com.crossoverjie.cim.client.service.impl.command;
2 2
  3 +import com.crossoverjie.cim.client.service.EchoService;
3 import com.crossoverjie.cim.client.service.InnerCommand; 4 import com.crossoverjie.cim.client.service.InnerCommand;
4 import com.crossoverjie.cim.client.service.MsgHandle; 5 import com.crossoverjie.cim.client.service.MsgHandle;
5 import org.slf4j.Logger; 6 import org.slf4j.Logger;
@@ -22,9 +23,13 @@ public class CloseAIModelCommand implements InnerCommand { @@ -22,9 +23,13 @@ public class CloseAIModelCommand implements InnerCommand {
22 @Autowired 23 @Autowired
23 private MsgHandle msgHandle ; 24 private MsgHandle msgHandle ;
24 25
  26 + @Autowired
  27 + private EchoService echoService ;
  28 +
25 @Override 29 @Override
26 public void process(String msg) { 30 public void process(String msg) {
27 msgHandle.closeAIModel(); 31 msgHandle.closeAIModel();
28 - System.out.println("\033[31;4m" + "。゚(゚´ω`゚)゚。 AI 下线了!" + "\033[0m"); 32 +
  33 + echoService.echo("\033[31;4m" + "。゚(゚´ω`゚)゚。 AI 下线了!" + "\033[0m");
29 } 34 }
30 } 35 }
1 package com.crossoverjie.cim.client.service.impl.command; 1 package com.crossoverjie.cim.client.service.impl.command;
2 2
3 -import com.alibaba.fastjson.JSON; 3 +import com.crossoverjie.cim.client.service.EchoService;
4 import com.crossoverjie.cim.client.service.InnerCommand; 4 import com.crossoverjie.cim.client.service.InnerCommand;
5 import com.crossoverjie.cim.client.service.impl.ClientInfo; 5 import com.crossoverjie.cim.client.service.impl.ClientInfo;
6 import org.slf4j.Logger; 6 import org.slf4j.Logger;
@@ -23,10 +23,13 @@ public class EchoInfoCommand implements InnerCommand { @@ -23,10 +23,13 @@ public class EchoInfoCommand implements InnerCommand {
23 @Autowired 23 @Autowired
24 private ClientInfo clientInfo; 24 private ClientInfo clientInfo;
25 25
  26 + @Autowired
  27 + private EchoService echoService ;
  28 +
26 @Override 29 @Override
27 public void process(String msg) { 30 public void process(String msg) {
28 - LOGGER.info("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");  
29 - LOGGER.info("client info=[{}]", JSON.toJSONString(clientInfo.get()));  
30 - LOGGER.info("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); 31 + echoService.echo("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
  32 + echoService.echo("client info={}", clientInfo.get().getUserName());
  33 + echoService.echo("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
31 } 34 }
32 } 35 }
  1 +package com.crossoverjie.cim.client.service.impl.command;
  2 +
  3 +import com.crossoverjie.cim.client.service.EchoService;
  4 +import com.crossoverjie.cim.client.service.InnerCommand;
  5 +import com.vdurmont.emoji.Emoji;
  6 +import com.vdurmont.emoji.EmojiManager;
  7 +import com.vdurmont.emoji.EmojiParser;
  8 +import org.slf4j.Logger;
  9 +import org.slf4j.LoggerFactory;
  10 +import org.springframework.beans.factory.annotation.Autowired;
  11 +import org.springframework.stereotype.Service;
  12 +
  13 +import java.util.List;
  14 +
  15 +/**
  16 + * Function:
  17 + *
  18 + * @author crossoverJie
  19 + * Date: 2019-01-27 19:37
  20 + * @since JDK 1.8
  21 + */
  22 +@Service
  23 +public class EmojiCommand implements InnerCommand {
  24 + private final static Logger LOGGER = LoggerFactory.getLogger(EmojiCommand.class);
  25 +
  26 + @Autowired
  27 + private EchoService echoService ;
  28 +
  29 +
  30 + @Override
  31 + public void process(String msg) {
  32 + if (msg.split(" ").length <=1){
  33 + echoService.echo("incorrect commond, :emoji [option]") ;
  34 + return ;
  35 + }
  36 + String value = msg.split(" ")[1];
  37 + if (value != null) {
  38 + Integer index = Integer.parseInt(value);
  39 + List<Emoji> all = (List<Emoji>) EmojiManager.getAll();
  40 + all = all.subList(5 * index, 5 * index + 5);
  41 +
  42 + for (Emoji emoji : all) {
  43 + echoService.echo(EmojiParser.parseToAliases(emoji.getUnicode()) + "--->" + emoji.getUnicode());
  44 + }
  45 + }
  46 +
  47 + }
  48 +}
1 package com.crossoverjie.cim.client.service.impl.command; 1 package com.crossoverjie.cim.client.service.impl.command;
2 2
  3 +import com.crossoverjie.cim.client.service.EchoService;
3 import com.crossoverjie.cim.client.service.InnerCommand; 4 import com.crossoverjie.cim.client.service.InnerCommand;
4 import com.crossoverjie.cim.client.service.RouteRequest; 5 import com.crossoverjie.cim.client.service.RouteRequest;
5 import com.crossoverjie.cim.client.vo.res.OnlineUsersResVO; 6 import com.crossoverjie.cim.client.vo.res.OnlineUsersResVO;
@@ -25,6 +26,8 @@ public class PrefixSearchCommand implements InnerCommand { @@ -25,6 +26,8 @@ public class PrefixSearchCommand implements InnerCommand {
25 26
26 @Autowired 27 @Autowired
27 private RouteRequest routeRequest ; 28 private RouteRequest routeRequest ;
  29 + @Autowired
  30 + private EchoService echoService ;
28 31
29 @Override 32 @Override
30 public void process(String msg) { 33 public void process(String msg) {
@@ -41,7 +44,7 @@ public class PrefixSearchCommand implements InnerCommand { @@ -41,7 +44,7 @@ public class PrefixSearchCommand implements InnerCommand {
41 44
42 for (String res : list) { 45 for (String res : list) {
43 res = res.replace(key, "\033[31;4m" + key + "\033[0m"); 46 res = res.replace(key, "\033[31;4m" + key + "\033[0m");
44 - System.out.println(res); 47 + echoService.echo(res) ;
45 } 48 }
46 49
47 } catch (Exception e) { 50 } catch (Exception e) {
1 package com.crossoverjie.cim.client.service.impl.command; 1 package com.crossoverjie.cim.client.service.impl.command;
2 2
  3 +import com.crossoverjie.cim.client.service.EchoService;
3 import com.crossoverjie.cim.client.service.InnerCommand; 4 import com.crossoverjie.cim.client.service.InnerCommand;
4 import com.crossoverjie.cim.common.enums.SystemCommandEnum; 5 import com.crossoverjie.cim.common.enums.SystemCommandEnum;
5 import org.slf4j.Logger; 6 import org.slf4j.Logger;
6 import org.slf4j.LoggerFactory; 7 import org.slf4j.LoggerFactory;
  8 +import org.springframework.beans.factory.annotation.Autowired;
7 import org.springframework.stereotype.Service; 9 import org.springframework.stereotype.Service;
8 10
9 import java.util.Map; 11 import java.util.Map;
@@ -19,15 +21,18 @@ import java.util.Map; @@ -19,15 +21,18 @@ import java.util.Map;
19 public class PrintAllCommand implements InnerCommand { 21 public class PrintAllCommand implements InnerCommand {
20 private final static Logger LOGGER = LoggerFactory.getLogger(PrintAllCommand.class); 22 private final static Logger LOGGER = LoggerFactory.getLogger(PrintAllCommand.class);
21 23
  24 + @Autowired
  25 + private EchoService echoService ;
  26 +
22 @Override 27 @Override
23 public void process(String msg) { 28 public void process(String msg) {
24 Map<String, String> allStatusCode = SystemCommandEnum.getAllStatusCode(); 29 Map<String, String> allStatusCode = SystemCommandEnum.getAllStatusCode();
25 - LOGGER.warn("===================================="); 30 + echoService.echo("====================================");
26 for (Map.Entry<String, String> stringStringEntry : allStatusCode.entrySet()) { 31 for (Map.Entry<String, String> stringStringEntry : allStatusCode.entrySet()) {
27 String key = stringStringEntry.getKey(); 32 String key = stringStringEntry.getKey();
28 String value = stringStringEntry.getValue(); 33 String value = stringStringEntry.getValue();
29 - LOGGER.warn(key + "----->" + value); 34 + echoService.echo(key + "----->" + value);
30 } 35 }
31 - LOGGER.warn("===================================="); 36 + echoService.echo("====================================");
32 } 37 }
33 } 38 }
1 package com.crossoverjie.cim.client.service.impl.command; 1 package com.crossoverjie.cim.client.service.impl.command;
2 2
  3 +import com.crossoverjie.cim.client.service.EchoService;
3 import com.crossoverjie.cim.client.service.InnerCommand; 4 import com.crossoverjie.cim.client.service.InnerCommand;
4 import com.crossoverjie.cim.client.service.RouteRequest; 5 import com.crossoverjie.cim.client.service.RouteRequest;
5 import com.crossoverjie.cim.client.vo.res.OnlineUsersResVO; 6 import com.crossoverjie.cim.client.vo.res.OnlineUsersResVO;
@@ -25,16 +26,19 @@ public class PrintOnlineUsersCommand implements InnerCommand { @@ -25,16 +26,19 @@ public class PrintOnlineUsersCommand implements InnerCommand {
25 @Autowired 26 @Autowired
26 private RouteRequest routeRequest ; 27 private RouteRequest routeRequest ;
27 28
  29 + @Autowired
  30 + private EchoService echoService ;
  31 +
28 @Override 32 @Override
29 public void process(String msg) { 33 public void process(String msg) {
30 try { 34 try {
31 List<OnlineUsersResVO.DataBodyBean> onlineUsers = routeRequest.onlineUsers(); 35 List<OnlineUsersResVO.DataBodyBean> onlineUsers = routeRequest.onlineUsers();
32 36
33 - LOGGER.info("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); 37 + echoService.echo("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
34 for (OnlineUsersResVO.DataBodyBean onlineUser : onlineUsers) { 38 for (OnlineUsersResVO.DataBodyBean onlineUser : onlineUsers) {
35 - LOGGER.info("userId={}=====userName={}", onlineUser.getUserId(), onlineUser.getUserName()); 39 + echoService.echo("userId={}=====userName={}",onlineUser.getUserId(),onlineUser.getUserName());
36 } 40 }
37 - LOGGER.info("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); 41 + echoService.echo("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
38 42
39 } catch (Exception e) { 43 } catch (Exception e) {
40 LOGGER.error("Exception", e); 44 LOGGER.error("Exception", e);
1 package com.crossoverjie.cim.client.service.impl.command; 1 package com.crossoverjie.cim.client.service.impl.command;
2 2
  3 +import com.crossoverjie.cim.client.service.EchoService;
3 import com.crossoverjie.cim.client.service.InnerCommand; 4 import com.crossoverjie.cim.client.service.InnerCommand;
4 import com.crossoverjie.cim.client.service.MsgLogger; 5 import com.crossoverjie.cim.client.service.MsgLogger;
5 import org.slf4j.Logger; 6 import org.slf4j.Logger;
@@ -22,6 +23,9 @@ public class QueryHistoryCommand implements InnerCommand { @@ -22,6 +23,9 @@ public class QueryHistoryCommand implements InnerCommand {
22 @Autowired 23 @Autowired
23 private MsgLogger msgLogger ; 24 private MsgLogger msgLogger ;
24 25
  26 + @Autowired
  27 + private EchoService echoService ;
  28 +
25 @Override 29 @Override
26 public void process(String msg) { 30 public void process(String msg) {
27 String[] split = msg.split(" "); 31 String[] split = msg.split(" ");
@@ -29,6 +33,6 @@ public class QueryHistoryCommand implements InnerCommand { @@ -29,6 +33,6 @@ public class QueryHistoryCommand implements InnerCommand {
29 return; 33 return;
30 } 34 }
31 String res = msgLogger.query(split[1]); 35 String res = msgLogger.query(split[1]);
32 - System.out.println(res); 36 + echoService.echo(res);
33 } 37 }
34 } 38 }
1 package com.crossoverjie.cim.client.service.impl.command; 1 package com.crossoverjie.cim.client.service.impl.command;
2 2
3 import com.crossoverjie.cim.client.client.CIMClient; 3 import com.crossoverjie.cim.client.client.CIMClient;
  4 +import com.crossoverjie.cim.client.service.EchoService;
4 import com.crossoverjie.cim.client.service.InnerCommand; 5 import com.crossoverjie.cim.client.service.InnerCommand;
5 import com.crossoverjie.cim.client.service.MsgLogger; 6 import com.crossoverjie.cim.client.service.MsgLogger;
6 import com.crossoverjie.cim.client.service.RouteRequest; 7 import com.crossoverjie.cim.client.service.RouteRequest;
@@ -37,25 +38,29 @@ public class ShutDownCommand implements InnerCommand { @@ -37,25 +38,29 @@ public class ShutDownCommand implements InnerCommand {
37 @Resource(name = "callBackThreadPool") 38 @Resource(name = "callBackThreadPool")
38 private ThreadPoolExecutor executor; 39 private ThreadPoolExecutor executor;
39 40
  41 + @Autowired
  42 + private EchoService echoService ;
  43 +
40 44
41 @Autowired 45 @Autowired
42 private ShutDownMsg shutDownMsg ; 46 private ShutDownMsg shutDownMsg ;
43 47
44 @Override 48 @Override
45 public void process(String msg) { 49 public void process(String msg) {
46 - LOGGER.info("系统关闭中。。。。"); 50 + echoService.echo("cim client closing...");
47 shutDownMsg.shutdown(); 51 shutDownMsg.shutdown();
48 routeRequest.offLine(); 52 routeRequest.offLine();
49 msgLogger.stop(); 53 msgLogger.stop();
50 executor.shutdown(); 54 executor.shutdown();
51 try { 55 try {
52 while (!executor.awaitTermination(1, TimeUnit.SECONDS)) { 56 while (!executor.awaitTermination(1, TimeUnit.SECONDS)) {
53 - LOGGER.info("线程池关闭中。。。。"); 57 + echoService.echo("thread pool closing");
54 } 58 }
55 cimClient.close(); 59 cimClient.close();
56 } catch (InterruptedException e) { 60 } catch (InterruptedException e) {
57 LOGGER.error("InterruptedException", e); 61 LOGGER.error("InterruptedException", e);
58 } 62 }
  63 + echoService.echo("cim close success!");
59 System.exit(0); 64 System.exit(0);
60 } 65 }
61 } 66 }
@@ -6,47 +6,47 @@ server.port=8082 @@ -6,47 +6,47 @@ server.port=8082
6 # 是否打开swagger 6 # 是否打开swagger
7 swagger.enable = true 7 swagger.enable = true
8 8
9 -logging.level.root=info 9 +logging.level.root=error
10 10
11 #消息记录存放路径 11 #消息记录存放路径
12 cim.msg.logger.path = /opt/logs/cim/ 12 cim.msg.logger.path = /opt/logs/cim/
13 13
14 14
15 ###=======生产模拟======### 15 ###=======生产模拟======###
16 -# 群发消息  
17 -cim.group.route.request.url=http://45.78.28.220:8083/groupRoute  
18 -  
19 -# 私聊消息  
20 -cim.p2p.route.request.url=http://45.78.28.220:8083/p2pRoute  
21 -  
22 -# 登录并获取服务器ip+port  
23 -cim.server.route.request.url=http://45.78.28.220:8083/login  
24 -  
25 -# 在线用户  
26 -cim.server.online.user.url=http://45.78.28.220:8083/onlineUser  
27 -  
28 -# 清除路由信息  
29 -cim.clear.route.request.url=http://45.78.28.220:8083/offLine  
30 -  
31 -###=======本地模拟======###  
32 ## 群发消息 16 ## 群发消息
33 -#cim.group.route.request.url=http://localhost:8083/groupRoute 17 +#cim.group.route.request.url=http://45.78.28.220:8083/groupRoute
34 # 18 #
35 ## 私聊消息 19 ## 私聊消息
36 -#cim.p2p.route.request.url=http://localhost:8083/p2pRoute 20 +#cim.p2p.route.request.url=http://45.78.28.220:8083/p2pRoute
37 # 21 #
38 ## 登录并获取服务器ip+port 22 ## 登录并获取服务器ip+port
39 -#cim.server.route.request.url=http://localhost:8083/login 23 +#cim.server.route.request.url=http://45.78.28.220:8083/login
40 # 24 #
41 ## 在线用户 25 ## 在线用户
42 -#cim.server.online.user.url=http://localhost:8083/onlineUser 26 +#cim.server.online.user.url=http://45.78.28.220:8083/onlineUser
  27 +#
  28 +## 清除路由信息
  29 +#cim.clear.route.request.url=http://45.78.28.220:8083/offLine
  30 +
  31 +###=======本地模拟======###
  32 +# 群发消息
  33 +cim.group.route.request.url=http://localhost:8083/groupRoute
  34 +
  35 +# 私聊消息
  36 +cim.p2p.route.request.url=http://localhost:8083/p2pRoute
  37 +
  38 +# 登录并获取服务器ip+port
  39 +cim.server.route.request.url=http://localhost:8083/login
  40 +
  41 +# 在线用户
  42 +cim.server.online.user.url=http://localhost:8083/onlineUser
43 43
44 -# 清除路由信息  
45 -#cim.clear.route.request.url=http://localhost:8083/offLine 44 + 清除路由信息
  45 +cim.clear.route.request.url=http://localhost:8083/offLine
46 46
47 # 客户端唯一ID 47 # 客户端唯一ID
48 -cim.user.id=1551267098213  
49 -cim.user.userName=test3 48 +cim.user.id=1566914867344
  49 +cim.user.userName=zhangsan
50 50
51 # 回调线程队列大小 51 # 回调线程队列大小
52 cim.callback.thread.queue.size = 2 52 cim.callback.thread.queue.size = 2
@@ -4,13 +4,18 @@ package com.crossoverjie.cim.server.test; @@ -4,13 +4,18 @@ package com.crossoverjie.cim.server.test;
4 import com.alibaba.fastjson.JSON; 4 import com.alibaba.fastjson.JSON;
5 import com.crossoverjie.cim.client.vo.res.CIMServerResVO; 5 import com.crossoverjie.cim.client.vo.res.CIMServerResVO;
6 import com.crossoverjie.cim.client.vo.res.OnlineUsersResVO; 6 import com.crossoverjie.cim.client.vo.res.OnlineUsersResVO;
  7 +import com.vdurmont.emoji.EmojiParser;
7 import org.junit.Test; 8 import org.junit.Test;
8 import org.slf4j.Logger; 9 import org.slf4j.Logger;
9 import org.slf4j.LoggerFactory; 10 import org.slf4j.LoggerFactory;
10 11
11 import java.io.IOException; 12 import java.io.IOException;
12 import java.nio.charset.Charset; 13 import java.nio.charset.Charset;
13 -import java.nio.file.*; 14 +import java.nio.file.Files;
  15 +import java.nio.file.LinkOption;
  16 +import java.nio.file.Path;
  17 +import java.nio.file.Paths;
  18 +import java.nio.file.StandardOpenOption;
14 import java.time.LocalDate; 19 import java.time.LocalDate;
15 import java.util.ArrayList; 20 import java.util.ArrayList;
16 import java.util.Arrays; 21 import java.util.Arrays;
@@ -179,5 +184,24 @@ public class CommonTest { @@ -179,5 +184,24 @@ public class CommonTest {
179 } catch (IOException e) { 184 } catch (IOException e) {
180 LOGGER.info("IOException", e); 185 LOGGER.info("IOException", e);
181 } 186 }
  187 +
  188 + }
  189 +
  190 + @Test
  191 + public void emoji() throws Exception{
  192 + String str = "An :grinning:awesome :smiley:string &#128516;with a few :wink:emojis!";
  193 + String result = EmojiParser.parseToUnicode(str);
  194 + System.out.println(result);
  195 +
  196 +
  197 + result = EmojiParser.parseToAliases(str);
  198 + System.out.println(result);
  199 +//
  200 +// Collection<Emoji> all = EmojiManager.getAll();
  201 +// for (Emoji emoji : all) {
  202 +// System.out.println(EmojiParser.parseToAliases(emoji.getUnicode()) + "--->" + emoji.getUnicode() );
  203 +// }
  204 +
182 } 205 }
  206 +
183 } 207 }
  1 +package com.crossoverjie.cim.server.test;
  2 +
  3 +import org.junit.Assert;
  4 +import org.junit.Test;
  5 +
  6 +/**
  7 + * Function:
  8 + *
  9 + * @author crossoverJie
  10 + * Date: 2019-08-28 01:47
  11 + * @since JDK 1.8
  12 + */
  13 +public class EchoTest {
  14 + @Test
  15 + public void echo() {
  16 + String msg = "{} say,you {}";
  17 + String[] place = {"zhangsan", "haha"};
  18 +
  19 + String log = log(msg, place);
  20 + System.out.println(log);
  21 + Assert.assertEquals(log,"zhangsan say,you haha");
  22 + }
  23 +
  24 + @Test
  25 + public void echo2() {
  26 + String msg = "{} say,you {},zhangsan say {}";
  27 + String[] place = {"zhangsan", "haha", "nihao"};
  28 +
  29 + String log = log(msg, place);
  30 + System.out.println(log);
  31 + Assert.assertEquals(log,"zhangsan say,you haha,zhangsan say nihao");
  32 + }
  33 +
  34 + @Test
  35 + public void echo3() {
  36 + String msg = "see you {},zhangsan say";
  37 + String[] place = {"zhangsan"};
  38 +
  39 + String log = log(msg, place);
  40 + System.out.println(log);
  41 + Assert.assertEquals(log,"see you zhangsan,zhangsan say");
  42 + }
  43 + @Test
  44 + public void echo4() {
  45 + String msg = "{}see you,zhangsan say";
  46 + String[] place = {"!!!"};
  47 +
  48 + String log = log(msg, place);
  49 + System.out.println(log);
  50 + Assert.assertEquals(log,"!!!see you,zhangsan say");
  51 + }
  52 + @Test
  53 + public void echo5() {
  54 + String msg = "see you,zhangsan say{}";
  55 + String[] place = {"!!!"};
  56 +
  57 + String log = log(msg, place);
  58 + System.out.println(log);
  59 + Assert.assertEquals(log,"see you,zhangsan say!!!");
  60 + }
  61 +
  62 + @Test
  63 + public void echo6() {
  64 + String msg = "see you,zhangsan say";
  65 + String[] place = {""};
  66 +
  67 + String log = log(msg, place);
  68 + System.out.println(log);
  69 + Assert.assertEquals(log,"see you,zhangsan say");
  70 + }
  71 +
  72 + private String log(String msg, String... place) {
  73 + StringBuilder sb = new StringBuilder();
  74 + int k = 0;
  75 + for (int i = 0; i < place.length; i++) {
  76 + int index = msg.indexOf("{}", k);
  77 +
  78 + if (index == -1){
  79 + return msg;
  80 + }
  81 +
  82 + if (index != 0) {
  83 + sb.append(msg, k, index);
  84 + sb.append(place[i]);
  85 +
  86 + if (place.length == 1) {
  87 + sb.append(msg, index + 2, msg.length());
  88 + }
  89 +
  90 + } else {
  91 + sb.append(place[i]);
  92 + if (place.length == 1) {
  93 + sb.append(msg, index + 2, msg.length());
  94 + }
  95 + }
  96 +
  97 + k = index + 2;
  98 + }
  99 + return sb.toString();
  100 + }
  101 +}
@@ -19,6 +19,7 @@ public enum SystemCommandEnum { @@ -19,6 +19,7 @@ public enum SystemCommandEnum {
19 AI(":ai ","开启 AI 模式","OpenAIModelCommand"), 19 AI(":ai ","开启 AI 模式","OpenAIModelCommand"),
20 QAI(":qai ","关闭 AI 模式","CloseAIModelCommand"), 20 QAI(":qai ","关闭 AI 模式","CloseAIModelCommand"),
21 PREFIX(":pu ","模糊匹配用户","PrefixSearchCommand"), 21 PREFIX(":pu ","模糊匹配用户","PrefixSearchCommand"),
  22 + EMOJI(":emoji ","emoji 表情列表","EmojiCommand"),
22 INFO(":info ","获取客户端信息","EchoInfoCommand") 23 INFO(":info ","获取客户端信息","EchoInfoCommand")
23 24
24 ; 25 ;
@@ -153,7 +153,7 @@ public class AccountServiceRedisImpl implements AccountService { @@ -153,7 +153,7 @@ public class AccountServiceRedisImpl implements AccountService {
153 CIMUserInfo cimUserInfo = userInfoCacheService.loadUserInfoByUserId(sendUserId); 153 CIMUserInfo cimUserInfo = userInfoCacheService.loadUserInfoByUserId(sendUserId);
154 154
155 JSONObject jsonObject = new JSONObject(); 155 JSONObject jsonObject = new JSONObject();
156 - jsonObject.put("msg", cimUserInfo.getUserName() + ":【" + groupReqVO.getMsg() + "】"); 156 + jsonObject.put("msg", cimUserInfo.getUserName() + ":" + groupReqVO.getMsg());
157 jsonObject.put("userId", groupReqVO.getUserId()); 157 jsonObject.put("userId", groupReqVO.getUserId());
158 RequestBody requestBody = RequestBody.create(mediaType, jsonObject.toString()); 158 RequestBody requestBody = RequestBody.create(mediaType, jsonObject.toString());
159 159
@@ -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:2182 16 +app.zk.addr=ip:port
17 17
18 # zk 连接超时时限 18 # zk 连接超时时限
19 app.zk.connect.timeout=15000 19 app.zk.connect.timeout=15000
@@ -37,10 +37,11 @@ app.route.way=com.crossoverjie.cim.common.route.algorithm.consistenthash.Consist @@ -37,10 +37,11 @@ app.route.way=com.crossoverjie.cim.common.route.algorithm.consistenthash.Consist
37 app.route.way.consitenthash=com.crossoverjie.cim.common.route.algorithm.consistenthash.TreeMapConsistentHash 37 app.route.way.consitenthash=com.crossoverjie.cim.common.route.algorithm.consistenthash.TreeMapConsistentHash
38 38
39 # Redis 配置 39 # Redis 配置
40 -spring.redis.host=47.98.194.60 40 +spring.redis.host=xx
41 spring.redis.port=6379 41 spring.redis.port=6379
42 spring.redis.pool.max-active=100 42 spring.redis.pool.max-active=100
43 spring.redis.pool.max-idle=100 43 spring.redis.pool.max-idle=100
44 spring.redis.pool.max-wait=1000 44 spring.redis.pool.max-wait=1000
45 spring.redis.pool.min-idle=10 45 spring.redis.pool.min-idle=10
  46 +spring.redis.password=xx
46 47
@@ -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:2182 28 +app.zk.addr=ip:port
29 29
30 # zk 连接超时时限 30 # zk 连接超时时限
31 app.zk.connect.timeout=15000 31 app.zk.connect.timeout=15000
@@ -36,5 +36,5 @@ app.zk.root=/route @@ -36,5 +36,5 @@ app.zk.root=/route
36 # 清除路由信息 36 # 清除路由信息
37 cim.clear.route.request.url=http://localhost:8083/offLine 37 cim.clear.route.request.url=http://localhost:8083/offLine
38 38
39 -# 检测多少秒没有收到客户端心跳后服务端关闭连接 39 +# 检测多少秒没有收到客户端心跳后服务端关闭连接 单位秒
40 cim.heartbeat.time = 30 40 cim.heartbeat.time = 30
1 -<?xml version="1.0" encoding="UTF-8"?>  
2 -<project xmlns="http://maven.apache.org/POM/4.0.0"  
3 - xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
4 - xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">  
5 - <parent>  
6 - <artifactId>cim</artifactId>  
7 - <groupId>com.crossoverjie.netty</groupId>  
8 - <version>1.0.0-SNAPSHOT</version>  
9 - </parent>  
10 - <modelVersion>4.0.0</modelVersion>  
11 -  
12 - <artifactId>cim-zk</artifactId>  
13 -  
14 -  
15 -  
16 - <properties>  
17 - <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>  
18 - <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>  
19 - <java.version>1.8</java.version>  
20 - </properties>  
21 -  
22 - <dependencies>  
23 - <dependency>  
24 - <groupId>com.crossoverjie.netty</groupId>  
25 - <artifactId>cim-common</artifactId>  
26 - <exclusions>  
27 - <exclusion>  
28 - <artifactId>log4j</artifactId>  
29 - <groupId>log4j</groupId>  
30 - </exclusion>  
31 - </exclusions>  
32 - </dependency>  
33 -  
34 -  
35 - <dependency>  
36 - <groupId>io.springfox</groupId>  
37 - <artifactId>springfox-swagger2</artifactId>  
38 - <scope>compile</scope>  
39 - </dependency>  
40 - <dependency>  
41 - <groupId>io.springfox</groupId>  
42 - <artifactId>springfox-swagger-ui</artifactId>  
43 - </dependency>  
44 -  
45 - <dependency>  
46 - <groupId>org.springframework.boot</groupId>  
47 - <artifactId>spring-boot-starter-web</artifactId>  
48 - </dependency>  
49 - <dependency>  
50 - <groupId>org.springframework.boot</groupId>  
51 - <artifactId>spring-boot-starter-test</artifactId>  
52 - <scope>test</scope>  
53 - </dependency>  
54 -  
55 - <dependency>  
56 - <groupId>org.springframework.boot</groupId>  
57 - <artifactId>spring-boot-configuration-processor</artifactId>  
58 - <optional>true</optional>  
59 - </dependency>  
60 -  
61 -  
62 - <dependency>  
63 - <groupId>org.springframework.boot</groupId>  
64 - <artifactId>spring-boot-starter-actuator</artifactId>  
65 - </dependency>  
66 -  
67 - <dependency>  
68 - <groupId>de.codecentric</groupId>  
69 - <artifactId>spring-boot-admin-starter-client</artifactId>  
70 - </dependency>  
71 -  
72 - <dependency>  
73 - <groupId>ch.qos.logback</groupId>  
74 - <artifactId>logback-classic</artifactId>  
75 - </dependency>  
76 - <dependency>  
77 - <groupId>org.slf4j</groupId>  
78 - <artifactId>slf4j-api</artifactId>  
79 - </dependency>  
80 - <dependency>  
81 - <groupId>ch.qos.logback</groupId>  
82 - <artifactId>logback-core</artifactId>  
83 - </dependency>  
84 -  
85 -  
86 - <dependency>  
87 - <groupId>junit</groupId>  
88 - <artifactId>junit</artifactId>  
89 - </dependency>  
90 -  
91 - <dependency>  
92 - <groupId>com.alibaba</groupId>  
93 - <artifactId>fastjson</artifactId>  
94 - </dependency>  
95 -  
96 - <dependency>  
97 - <groupId>com.google.guava</groupId>  
98 - <artifactId>guava</artifactId>  
99 - </dependency>  
100 - </dependencies>  
101 -  
102 -  
103 - <build>  
104 - <plugins>  
105 - <!-- spring-boot-maven-plugin (提供了直接运行项目的插件:如果是通过parent方式继承spring-boot-starter-parent则不用此插件) -->  
106 - <plugin>  
107 - <groupId>org.springframework.boot</groupId>  
108 - <artifactId>spring-boot-maven-plugin</artifactId>  
109 - <executions>  
110 - <execution>  
111 - <goals>  
112 - <goal>repackage</goal>  
113 - </goals>  
114 - </execution>  
115 - </executions>  
116 - </plugin>  
117 - </plugins>  
118 - </build>  
119 -  
120 -</project>  
1 -package com.crossoverjie.cim.server.zk;  
2 -  
3 -import com.crossoverjie.cim.server.zk.util.AppConfiguration;  
4 -import com.crossoverjie.cim.server.zk.thread.RegistryZK;  
5 -import com.crossoverjie.cim.server.zk.util.ZKit;  
6 -import org.slf4j.Logger;  
7 -import org.slf4j.LoggerFactory;  
8 -import org.springframework.beans.factory.annotation.Autowired;  
9 -import org.springframework.boot.CommandLineRunner;  
10 -import org.springframework.boot.SpringApplication;  
11 -import org.springframework.boot.autoconfigure.SpringBootApplication;  
12 -  
13 -import java.net.InetAddress;  
14 -  
15 -/**  
16 - * @author crossoverJie  
17 - */  
18 -@SpringBootApplication  
19 -public class Application implements CommandLineRunner{  
20 -  
21 - private final static Logger LOGGER = LoggerFactory.getLogger(Application.class);  
22 -  
23 - @Autowired  
24 - private AppConfiguration appConfiguration ;  
25 -  
26 - @Autowired  
27 - private static ZKit zkUtil ;  
28 -  
29 - public static void main(String[] args) {  
30 - SpringApplication.run(Application.class, args);  
31 - LOGGER.info("启动应用成功");  
32 -  
33 - }  
34 -  
35 - @Override  
36 - public void run(String... args) throws Exception {  
37 - //获得本机IP  
38 - String addr = InetAddress.getLocalHost().getHostAddress();  
39 - Thread thread = new Thread(new RegistryZK(addr, appConfiguration.getPort()));  
40 - thread.setName("registry-zk");  
41 - //thread.start() ;  
42 - }  
43 -}  
1 -package com.crossoverjie.cim.server.zk.cache;  
2 -  
3 -import com.crossoverjie.cim.server.zk.util.ZKit;  
4 -import com.google.common.cache.LoadingCache;  
5 -import org.springframework.beans.factory.annotation.Autowired;  
6 -import org.springframework.stereotype.Component;  
7 -  
8 -import java.util.ArrayList;  
9 -import java.util.List;  
10 -import java.util.Map;  
11 -import java.util.concurrent.atomic.AtomicLong;  
12 -  
13 -/**  
14 - * Function: 服务器节点缓存  
15 - *  
16 - * @author crossoverJie  
17 - * Date: 2018/8/19 01:31  
18 - * @since JDK 1.8  
19 - */  
20 -@Component  
21 -public class ServerCache {  
22 -  
23 -  
24 - @Autowired  
25 - private LoadingCache<String, String> cache;  
26 -  
27 - @Autowired  
28 - private ZKit zkUtil;  
29 -  
30 - private AtomicLong index = new AtomicLong();  
31 -  
32 -  
33 - public void addCache(String key) {  
34 - cache.put(key, key);  
35 - }  
36 -  
37 -  
38 - /**  
39 - * 更新所有缓存/先删除 再新增  
40 - *  
41 - * @param currentChilds  
42 - */  
43 - public void updateCache(List<String> currentChilds) {  
44 - cache.invalidateAll();  
45 - for (String currentChild : currentChilds) {  
46 - String key = currentChild.split("-")[1];  
47 - addCache(key);  
48 - }  
49 - }  
50 -  
51 -  
52 - /**  
53 - * 获取所有的服务列表  
54 - *  
55 - * @return  
56 - */  
57 - public List<String> getAll() {  
58 -  
59 - List<String> list = new ArrayList<>();  
60 -  
61 - if (cache.size() == 0) {  
62 - List<String> allNode = zkUtil.getAllNode();  
63 - for (String node : allNode) {  
64 - String key = node.split("-")[1];  
65 - addCache(key);  
66 - }  
67 - }  
68 - for (Map.Entry<String, String> entry : cache.asMap().entrySet()) {  
69 - list.add(entry.getKey());  
70 - }  
71 - return list;  
72 -  
73 - }  
74 -  
75 - /**  
76 - * 选取服务器  
77 - *  
78 - * @return  
79 - */  
80 - public String selectServer() {  
81 - List<String> all = getAll();  
82 - if (all.size() == 0) {  
83 - throw new RuntimeException("路由列表为空");  
84 - }  
85 - Long position = index.incrementAndGet() % all.size();  
86 - if (position < 0) {  
87 - position = 0L;  
88 - }  
89 -  
90 - return all.get(position.intValue());  
91 - }  
92 -}  
1 -package com.crossoverjie.cim.server.zk.config;  
2 -  
3 -import com.crossoverjie.cim.server.zk.util.AppConfiguration;  
4 -import com.google.common.cache.CacheBuilder;  
5 -import com.google.common.cache.CacheLoader;  
6 -import com.google.common.cache.LoadingCache;  
7 -import org.I0Itec.zkclient.ZkClient;  
8 -import org.springframework.beans.factory.annotation.Autowired;  
9 -import org.springframework.context.annotation.Bean;  
10 -import org.springframework.context.annotation.Configuration;  
11 -  
12 -/**  
13 - * Function:  
14 - *  
15 - * @author crossoverJie  
16 - * Date: 2018/8/24 01:28  
17 - * @since JDK 1.8  
18 - */  
19 -@Configuration  
20 -public class AppConfig {  
21 -  
22 - @Autowired  
23 - private AppConfiguration appConfiguration ;  
24 -  
25 - @Bean  
26 - public ZkClient buildZKClient(){  
27 - return new ZkClient(appConfiguration.getZkAddr(), 5000);  
28 - }  
29 -  
30 -  
31 - @Bean  
32 - public LoadingCache<String,String> buildCache(){  
33 - return CacheBuilder.newBuilder()  
34 - .build(new CacheLoader<String, String>() {  
35 - @Override  
36 - public String load(String s) throws Exception {  
37 - return null;  
38 - }  
39 - });  
40 - }  
41 -}  
1 -package com.crossoverjie.cim.server.zk.config;  
2 -  
3 -import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;  
4 -import org.springframework.context.annotation.Bean;  
5 -import org.springframework.context.annotation.Configuration;  
6 -import springfox.documentation.builders.ApiInfoBuilder;  
7 -import springfox.documentation.builders.PathSelectors;  
8 -import springfox.documentation.builders.RequestHandlerSelectors;  
9 -import springfox.documentation.service.ApiInfo;  
10 -import springfox.documentation.spi.DocumentationType;  
11 -import springfox.documentation.spring.web.plugins.Docket;  
12 -import springfox.documentation.swagger2.annotations.EnableSwagger2;  
13 -  
14 -  
15 -@Configuration  
16 -@EnableSwagger2  
17 -/** 是否打开swagger **/  
18 -@ConditionalOnExpression("'${swagger.enable}' == 'true'")  
19 -public class SwaggerConfig {  
20 -  
21 -  
22 - @Bean  
23 - public Docket createRestApi() {  
24 - return new Docket(DocumentationType.SWAGGER_2)  
25 - .apiInfo(apiInfo())  
26 - .select()  
27 - .apis(RequestHandlerSelectors.basePackage("com.crossoverjie.netty.action.zk.controller"))  
28 - .paths(PathSelectors.any())  
29 - .build();  
30 - }  
31 -  
32 - private ApiInfo apiInfo() {  
33 - return new ApiInfoBuilder()  
34 - .title("netty-action-zk api")  
35 - .description("netty-action-zk api")  
36 - .termsOfServiceUrl("https://crossoverJie.top")  
37 - .contact("crossoverJie")  
38 - .version("1.0.0")  
39 - .build();  
40 - }  
41 -  
42 -}  
1 -package com.crossoverjie.cim.server.zk.controller;  
2 -  
3 -import com.crossoverjie.cim.common.enums.StatusEnum;  
4 -import com.crossoverjie.cim.common.res.BaseResponse;  
5 -import com.crossoverjie.cim.server.zk.cache.ServerCache;  
6 -import io.swagger.annotations.ApiOperation;  
7 -import org.springframework.beans.factory.annotation.Autowired;  
8 -import org.springframework.stereotype.Controller;  
9 -import org.springframework.web.bind.annotation.RequestMapping;  
10 -import org.springframework.web.bind.annotation.RequestMethod;  
11 -import org.springframework.web.bind.annotation.ResponseBody;  
12 -  
13 -import java.util.List;  
14 -  
15 -/**  
16 - * Function:  
17 - *  
18 - * @author crossoverJie  
19 - * Date: 22/05/2018 14:46  
20 - * @since JDK 1.8  
21 - */  
22 -@Controller  
23 -@RequestMapping("/")  
24 -public class IndexController {  
25 -  
26 -  
27 - @Autowired  
28 - private ServerCache serverCache ;  
29 -  
30 - /**  
31 - * 获取所有路由节点  
32 - * @return  
33 - */  
34 - @ApiOperation("获取所有路由节点")  
35 - @RequestMapping(value = "getAllRoute",method = RequestMethod.POST)  
36 - @ResponseBody()  
37 - public BaseResponse<List<String>> getAllRoute(){  
38 - BaseResponse<List<String>> res = new BaseResponse();  
39 - List<String> all = serverCache.getAll();  
40 - res.setDataBody(all);  
41 - res.setCode(StatusEnum.SUCCESS.getCode()) ;  
42 - res.setMessage(StatusEnum.SUCCESS.getMessage()) ;  
43 - return res ;  
44 - }  
45 -  
46 - /**  
47 - * 获取所有路由节点  
48 - * @return  
49 - */  
50 - @ApiOperation("获取所有路由节点")  
51 - @RequestMapping(value = "getOneOfRoute",method = RequestMethod.POST)  
52 - @ResponseBody()  
53 - public BaseResponse<String> getOneOfRoute(){  
54 - BaseResponse<String> res = new BaseResponse();  
55 - String server = serverCache.selectServer();  
56 - res.setDataBody(server);  
57 - res.setCode(StatusEnum.SUCCESS.getCode()) ;  
58 - res.setMessage(StatusEnum.SUCCESS.getMessage()) ;  
59 - return res ;  
60 - }  
61 -  
62 -  
63 -  
64 -  
65 -}  
1 -package com.crossoverjie.cim.server.zk.thread;  
2 -  
3 -import com.crossoverjie.cim.server.zk.util.AppConfiguration;  
4 -import com.crossoverjie.cim.server.zk.util.SpringBeanFactory;  
5 -import com.crossoverjie.cim.server.zk.util.ZKit;  
6 -import org.slf4j.Logger;  
7 -import org.slf4j.LoggerFactory;  
8 -  
9 -/**  
10 - * Function:  
11 - *  
12 - * @author crossoverJie  
13 - * Date: 2018/8/24 01:37  
14 - * @since JDK 1.8  
15 - */  
16 -public class RegistryZK implements Runnable {  
17 -  
18 - private static Logger logger = LoggerFactory.getLogger(RegistryZK.class);  
19 -  
20 - private ZKit zkUtil;  
21 -  
22 - private AppConfiguration appConfiguration ;  
23 -  
24 - private String ip;  
25 - private int port;  
26 -  
27 - public RegistryZK(String ip, int port) {  
28 - this.ip = ip;  
29 - this.port = port;  
30 - zkUtil = SpringBeanFactory.getBean(ZKit.class) ;  
31 - appConfiguration = SpringBeanFactory.getBean(AppConfiguration.class) ;  
32 - }  
33 -  
34 - @Override  
35 - public void run() {  
36 -  
37 - //创建父节点  
38 - zkUtil.createRootNode();  
39 -  
40 - //是否要将自己注册到 ZK  
41 - if (appConfiguration.isZkSwitch()){  
42 - String path = appConfiguration.getZkRoot() + "/ip-" + ip + ":" + port;  
43 - zkUtil.createNode(path, path);  
44 - logger.info("注册 zookeeper 成功,msg=[{}]", path);  
45 - }  
46 -  
47 - //注册监听服务  
48 - zkUtil.subscribeEvent(appConfiguration.getZkRoot());  
49 -  
50 - }  
51 -}  
1 -package com.crossoverjie.cim.server.zk.util;  
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("${app.zk.root}")  
17 - private String zkRoot;  
18 -  
19 - @Value("${app.zk.addr}")  
20 - private String zkAddr;  
21 -  
22 - @Value("${app.zk.switch}")  
23 - private boolean zkSwitch;  
24 -  
25 - @Value("${server.port}")  
26 - private int port;  
27 -  
28 - public int getPort() {  
29 - return port;  
30 - }  
31 -  
32 - public void setPort(int port) {  
33 - this.port = port;  
34 - }  
35 -  
36 - public String getZkRoot() {  
37 - return zkRoot;  
38 - }  
39 -  
40 - public void setZkRoot(String zkRoot) {  
41 - this.zkRoot = zkRoot;  
42 - }  
43 -  
44 - public String getZkAddr() {  
45 - return zkAddr;  
46 - }  
47 -  
48 - public void setZkAddr(String zkAddr) {  
49 - this.zkAddr = zkAddr;  
50 - }  
51 -  
52 - public boolean isZkSwitch() {  
53 - return zkSwitch;  
54 - }  
55 -  
56 - public void setZkSwitch(boolean zkSwitch) {  
57 - this.zkSwitch = zkSwitch;  
58 - }  
59 -}  
1 -package com.crossoverjie.cim.server.zk.util;  
2 -  
3 -import org.springframework.beans.BeansException;  
4 -import org.springframework.context.ApplicationContext;  
5 -import org.springframework.context.ApplicationContextAware;  
6 -import org.springframework.stereotype.Component;  
7 -  
8 -@Component  
9 -public final class SpringBeanFactory implements ApplicationContextAware{  
10 - private static ApplicationContext context;  
11 -  
12 - public static <T> T getBean(Class<T> c){  
13 - return context.getBean(c);  
14 - }  
15 -  
16 -  
17 - public static <T> T getBean(String name,Class<T> clazz){  
18 - return context.getBean(name,clazz);  
19 - }  
20 -  
21 - @Override  
22 - public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {  
23 - context = applicationContext;  
24 - }  
25 -  
26 -  
27 -}  
1 -package com.crossoverjie.cim.server.zk.util;  
2 -  
3 -import com.alibaba.fastjson.JSON;  
4 -import com.crossoverjie.cim.server.zk.cache.ServerCache;  
5 -import org.I0Itec.zkclient.IZkChildListener;  
6 -import org.I0Itec.zkclient.ZkClient;  
7 -import org.slf4j.Logger;  
8 -import org.slf4j.LoggerFactory;  
9 -import org.springframework.beans.factory.annotation.Autowired;  
10 -import org.springframework.stereotype.Component;  
11 -  
12 -import java.util.List;  
13 -  
14 -/**  
15 - * Function: Zookeeper 工具  
16 - *  
17 - * @author crossoverJie  
18 - * Date: 2018/8/19 00:33  
19 - * @since JDK 1.8  
20 - */  
21 -@Component  
22 -public class ZKit {  
23 -  
24 - private static Logger logger = LoggerFactory.getLogger(ZKit.class);  
25 -  
26 -  
27 - @Autowired  
28 - private ZkClient zkClient;  
29 -  
30 - @Autowired  
31 - private AppConfiguration appConfiguration ;  
32 -  
33 - @Autowired  
34 - private ServerCache serverCache ;  
35 -  
36 -  
37 - /**  
38 - * 创建父级节点  
39 - */  
40 - public void createRootNode(){  
41 - boolean exists = zkClient.exists(appConfiguration.getZkRoot());  
42 - if (exists){  
43 - return;  
44 - }  
45 -  
46 - //创建 root  
47 - zkClient.createPersistent(appConfiguration.getZkRoot()) ;  
48 - }  
49 -  
50 - /**  
51 - * 写入指定节点 临时目录  
52 - *  
53 - * @param path  
54 - * @param value  
55 - */  
56 - public void createNode(String path, String value) {  
57 - zkClient.createEphemeral(path, value);  
58 - }  
59 -  
60 -  
61 - /**  
62 - * 监听事件  
63 - *  
64 - * @param path  
65 - */  
66 - public void subscribeEvent(String path) {  
67 - zkClient.subscribeChildChanges(path, new IZkChildListener() {  
68 - @Override  
69 - public void handleChildChange(String parentPath, List<String> currentChilds) throws Exception {  
70 - logger.info("清除/更新本地缓存 parentPath=【{}】,currentChilds=【{}】", parentPath,currentChilds.toString());  
71 -  
72 - //更新所有缓存/先删除 再新增  
73 - serverCache.updateCache(currentChilds) ;  
74 - }  
75 - });  
76 -  
77 -  
78 - }  
79 -  
80 -  
81 - /**  
82 - * 获取所有注册节点  
83 - * @return  
84 - */  
85 - public List<String> getAllNode(){  
86 - List<String> children = zkClient.getChildren("/route");  
87 - logger.info("查询所有节点成功=【{}】", JSON.toJSONString(children));  
88 - return children;  
89 - }  
90 -  
91 - /**  
92 - * 关闭 ZK  
93 - */  
94 - public void closeZK() {  
95 - logger.info("正在关闭 ZK");  
96 - zkClient.close();  
97 - logger.info("关闭 ZK 成功");  
98 -  
99 - }  
100 -}  
1 -spring.application.name=cim-zk  
2 -  
3 -# web port  
4 -server.port=9083  
5 -  
6 -# 是否打开swagger  
7 -swagger.enable = true  
8 -  
9 -logging.level.root=info  
10 -  
11 -  
12 -  
13 -# 是否注册 zk  
14 -app.zk.switch=true  
15 -  
16 -# zk 地址  
17 -app.zk.addr=47.98.194.60:2181  
18 -  
19 -# zk 注册根节点  
20 -app.zk.root=/route  
@@ -13,7 +13,8 @@ @@ -13,7 +13,8 @@
13 13
14 14
15 ``` 15 ```
16 -spring.redis.host=47.98.194.60
spring.redis.port=6379 16 +spring.redis.host=xx
  17 +
spring.redis.port=6379
17 ``` 18 ```
18 19
19 其实所有的配置都是通过 `SpringBoot` 来加载的,看这个配置就知道了。 20 其实所有的配置都是通过 `SpringBoot` 来加载的,看这个配置就知道了。
@@ -30,7 +30,6 @@ @@ -30,7 +30,6 @@
30 <module>cim-server</module> 30 <module>cim-server</module>
31 <module>cim-client</module> 31 <module>cim-client</module>
32 <module>cim-common</module> 32 <module>cim-common</module>
33 - <module>cim-zk</module>  
34 <module>cim-forward-route</module> 33 <module>cim-forward-route</module>
35 </modules> 34 </modules>
36 35
@@ -107,4 +106,17 @@ @@ -107,4 +106,17 @@
107 </dependencies> 106 </dependencies>
108 </dependencyManagement> 107 </dependencyManagement>
109 108
  109 +
  110 + <build>
  111 + <plugins>
  112 + <plugin>
  113 + <groupId>org.apache.maven.plugins</groupId>
  114 + <artifactId>maven-compiler-plugin</artifactId>
  115 + <configuration>
  116 + <source>1.8</source>
  117 + <target>1.8</target>
  118 + </configuration>
  119 + </plugin>
  120 + </plugins>
  121 + </build>
110 </project> 122 </project>