Commit 7f50a93b by giaogiao

优化代码结构

parent c0ba524d
...@@ -14,21 +14,21 @@ import org.springframework.stereotype.Component; ...@@ -14,21 +14,21 @@ import org.springframework.stereotype.Component;
@Slf4j @Slf4j
public class NettyStart { public class NettyStart {
private final NettyChannelInitializer nettyChannelInitializer; private final NettyChannelInitializer nettyChannelInitializer;
private static final EventLoopGroup boss = new NioEventLoopGroup(1); private static final EventLoopGroup BOSS = new NioEventLoopGroup(1);
private static final EventLoopGroup work = new NioEventLoopGroup(); private static final EventLoopGroup WORK = new NioEventLoopGroup();
private static final ServerBootstrap serverBootstrap = new ServerBootstrap(); private static final ServerBootstrap SERVER_BOOTSTRAP = new ServerBootstrap();
static { static {
serverBootstrap.group(boss, work); SERVER_BOOTSTRAP.group(BOSS, WORK);
//Netty4使用对象池,重用缓冲区 //Netty4使用对象池,重用缓冲区
serverBootstrap.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); SERVER_BOOTSTRAP.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
serverBootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); SERVER_BOOTSTRAP.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
//设置 心跳保活 socket 的参数选项 keepAlive //设置 心跳保活 socket 的参数选项 keepAlive
serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE, true); SERVER_BOOTSTRAP.childOption(ChannelOption.SO_KEEPALIVE, true);
// 设置不延迟发送TCP_NODELAY=true // 设置不延迟发送TCP_NODELAY=true
serverBootstrap.childOption(ChannelOption.TCP_NODELAY, true); SERVER_BOOTSTRAP.childOption(ChannelOption.TCP_NODELAY, true);
// // 初始化服务端可连接队列 // // 初始化服务端可连接队列
// serverBootstrap.option(ChannelOption.SO_BACKLOG, 1000); // serverBootstrap.option(ChannelOption.SO_BACKLOG, 1000);
...@@ -39,7 +39,7 @@ public class NettyStart { ...@@ -39,7 +39,7 @@ public class NettyStart {
// serverBootstrap.option(ChannelOption.SO_SNDBUF, 256 * 1024); // serverBootstrap.option(ChannelOption.SO_SNDBUF, 256 * 1024);
// 配置io模型为nio非阻塞 // 配置io模型为nio非阻塞
serverBootstrap.channel(NioServerSocketChannel.class); SERVER_BOOTSTRAP.channel(NioServerSocketChannel.class);
} }
...@@ -58,16 +58,16 @@ public class NettyStart { ...@@ -58,16 +58,16 @@ public class NettyStart {
try { try {
//设置过滤器 //设置过滤器
serverBootstrap.childHandler(nettyChannelInitializer); SERVER_BOOTSTRAP.childHandler(nettyChannelInitializer);
// 服务器绑定端口监听 // 服务器绑定端口监听
ChannelFuture f = serverBootstrap.bind(port).sync(); ChannelFuture f = SERVER_BOOTSTRAP.bind(port).sync();
f.channel().closeFuture().sync(); f.channel().closeFuture().sync();
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} finally { } finally {
//关闭EventLoopGroup,释放掉所有资源包括创建的线程 //关闭EventLoopGroup,释放掉所有资源包括创建的线程
boss.shutdownGracefully(); BOSS.shutdownGracefully();
work.shutdownGracefully(); WORK.shutdownGracefully();
} }
} }
......
...@@ -85,7 +85,7 @@ public class PushClient { ...@@ -85,7 +85,7 @@ public class PushClient {
// Decode response string and get file_id from it // Decode response string and get file_id from it
JSONObject respJson = new JSONObject(result.toString()); JSONObject respJson = new JSONObject(result.toString());
String ret = respJson.getString("ret"); String ret = respJson.getString("ret");
if (!ret.equals("SUCCESS")) { if (!"SUCCESS".equals(ret)) {
throw new Exception("Failed to upload file"); throw new Exception("Failed to upload file");
} }
JSONObject data = respJson.getJSONObject("data"); JSONObject data = respJson.getJSONObject("data");
......
...@@ -101,8 +101,7 @@ public class ImClientLoginServiceImpl implements ImClientLoginService { ...@@ -101,8 +101,7 @@ public class ImClientLoginServiceImpl implements ImClientLoginService {
// 保存redis // 保存redis
// redisTemplate.opsForValue().set("client:" + imApplication.getAppKey() + ":" + imTokenVerify.getClientId(), generateToken); // redisTemplate.opsForValue().set("client:" + imApplication.getAppKey() + ":" + imTokenVerify.getClientId(), generateToken);
JwtToken jwtToken = new JwtToken() JwtToken jwtToken = JwtToken.build(generateToken, secret, jwtProperties.getExpireSecond(), imClient.getClientId(), imTokenVerify.getAppKey());
.build(generateToken, secret, jwtProperties.getExpireSecond(), imClient.getClientId(), imTokenVerify.getAppKey());
appLoginRedisService.cacheLoginInfo(jwtToken); appLoginRedisService.cacheLoginInfo(jwtToken);
......
...@@ -148,10 +148,10 @@ public class ImInboxServiceImpl extends BaseServiceImpl<ImInboxMapper, ImInbox> ...@@ -148,10 +148,10 @@ public class ImInboxServiceImpl extends BaseServiceImpl<ImInboxMapper, ImInbox>
private void sendMsgStatus(ImClient curentClient, ImApplication application, HashMap<String, String> stringStringHashMap, List<Long> msgIds) { private void sendMsgStatus(ImClient curentClient, ImApplication application, HashMap<String, String> stringStringHashMap, List<Long> msgIds) {
// 遍历消息id集合 // 遍历消息id集合
for (Long MsgId : msgIds) { for (Long msgId : msgIds) {
// 查询该消息 // 查询该消息
ImMessage imMessageDb = imMessageService.getById(MsgId); ImMessage imMessageDb = imMessageService.getById(msgId);
// 根据会话id查询该会话所有成员 // 根据会话id查询该会话所有成员
List<ImConversationMembers> membersList = imConversationMembersService.list( List<ImConversationMembers> membersList = imConversationMembersService.list(
...@@ -165,7 +165,7 @@ public class ImInboxServiceImpl extends BaseServiceImpl<ImInboxMapper, ImInbox> ...@@ -165,7 +165,7 @@ public class ImInboxServiceImpl extends BaseServiceImpl<ImInboxMapper, ImInbox>
// 消息实体 // 消息实体
ImMessage imMessage = new ImMessage(); ImMessage imMessage = new ImMessage();
imMessage.setId(MsgId); imMessage.setId(msgId);
imMessage.setCreateTime(new Date()); imMessage.setCreateTime(new Date());
imMessage.setFkAppid(curentClient.getFkAppid()); imMessage.setFkAppid(curentClient.getFkAppid());
imMessage.setSender(curentClient.getId()); imMessage.setSender(curentClient.getId());
......
...@@ -103,8 +103,7 @@ public class ImMessageServiceImpl extends BaseServiceImpl<ImMessageMapper, ImMes ...@@ -103,8 +103,7 @@ public class ImMessageServiceImpl extends BaseServiceImpl<ImMessageMapper, ImMes
return ApiResult.fail(); return ApiResult.fail();
} }
boolean isOK = this.updateById(imMessage); if (this.updateById(imMessage)) {
if (isOK) {
return ApiResult.ok(); return ApiResult.ok();
} else { } else {
return ApiResult.fail(); return ApiResult.fail();
......
...@@ -20,12 +20,12 @@ public class ResponseModel<T> implements Serializable { ...@@ -20,12 +20,12 @@ public class ResponseModel<T> implements Serializable {
public static final Integer ONLINE_EVENT_MSG = 3; public static final Integer ONLINE_EVENT_MSG = 3;
/** /**
* 下发在线消息 * 下发在线基本类型消息
*/ */
public static final Integer ONLINE_MSG = 2; public static final Integer ONLINE_MSG = 2;
/** /**
* 响应数据 * 响应数据类型
*/ */
public static final Integer RES = 1; public static final Integer RES = 1;
......
...@@ -44,6 +44,10 @@ import java.util.List; ...@@ -44,6 +44,10 @@ import java.util.List;
@Slf4j @Slf4j
public class ImConcreteReceiveStrategy extends AbstractReceiveStrategy { public class ImConcreteReceiveStrategy extends AbstractReceiveStrategy {
private static final String TO_CONVERSATION_KEY = "toConversation";
private static final String MSG_ID = "msgId";
@Autowired @Autowired
private ImClientBlacklistService imClientBlacklistService; private ImClientBlacklistService imClientBlacklistService;
...@@ -82,24 +86,21 @@ public class ImConcreteReceiveStrategy extends AbstractReceiveStrategy { ...@@ -82,24 +86,21 @@ public class ImConcreteReceiveStrategy extends AbstractReceiveStrategy {
} }
// 查询发送者client // 查询发送者client
ImClient imClientSender = imClientService.getOne(new QueryWrapper<ImClient>().lambda() ImClient imClientSender = getClientSender(clientUniId, imApplication);
.eq(ImClient::getFkAppid, imApplication.getId())
.eq(ImClient::getClientId, clientUniId));
if (imClientSender == null) { if (imClientSender == null) {
log.error("imClientSender为空");
return; return;
} }
JsonMapper jsonMapper = new JsonMapper();
// 获取会话id // 获取会话id
Long toConversationId = Long.valueOf(receiveModel.getData().get("toConversation").toString()); if (receiveModel.getData().get(TO_CONVERSATION_KEY) == null) {
receiveModel.getData().remove("toConversation"); return;
}
Long toConversationId = Long.valueOf(receiveModel.getData().get(TO_CONVERSATION_KEY).toString());
receiveModel.getData().remove(TO_CONVERSATION_KEY);
// 生成消息id
long messageId = SnowflakeUtil.getId();
String content = null; String content = null;
JsonMapper jsonMapper = new JsonMapper();
try { try {
content = jsonMapper.writeValueAsString(receiveModel.getData()); content = jsonMapper.writeValueAsString(receiveModel.getData());
} catch (JsonProcessingException e) { } catch (JsonProcessingException e) {
...@@ -120,52 +121,17 @@ public class ImConcreteReceiveStrategy extends AbstractReceiveStrategy { ...@@ -120,52 +121,17 @@ public class ImConcreteReceiveStrategy extends AbstractReceiveStrategy {
// 判断为单聊 // 判断为单聊
if (membersList.size() == 1) { if (membersList.size() == 1) {
// 判断是否被拉黑 // 拉黑逻辑
boolean beBlack = imClientBlacklistService.isBeBlack(membersList.get(0).getFkClientId(), imClientSender.getId()); if (black(receiveModel, appKey, clientUniId, imClientSender, membersList)) {
if (beBlack) {
log.debug("被对方拉黑了");
// 响应发送方
ResponseModel<HashMap<String, Long>> responseModel = new ResponseModel<>();
ApiResult<Boolean> result = ApiResult.result(ApiCode.IS_BE_BLACK);
responseModel.setCmd(ResponseModel.RES);
responseModel.setCode(result.getCode());
responseModel.setMsg(result.getMessage());
responseModel.setReqId(receiveModel.getReqId());
writeDataService.write(responseModel, appKey, clientUniId);
return;
}
// 是否把对方拉黑
boolean black = imClientBlacklistService.isBeBlack(imClientSender.getId(), membersList.get(0).getFkClientId());
if (black) {
log.debug("你把对方拉黑了");
// 响应发送方
ResponseModel<HashMap<String, Long>> responseModel = new ResponseModel<>();
ApiResult<Boolean> result = ApiResult.result(ApiCode.IS_TO_BLACK);
responseModel.setCmd(ResponseModel.RES);
responseModel.setCode(result.getCode());
responseModel.setMsg(result.getMessage());
responseModel.setReqId(receiveModel.getReqId());
writeDataService.write(responseModel, appKey, clientUniId);
return; return;
} }
} }
// 保存消息 // 生成消息id
ImMessage imMessage = new ImMessage(); long messageId = SnowflakeUtil.getId();
imMessage.setId(messageId); // 保存消息至消息表
imMessage.setCreateTime(new Date()); ImMessage imMessage = saveImMessage(imApplication, imClientSender, toConversationId, messageId, content);
imMessage.setFkAppid(imApplication.getId());
imMessage.setSender(imClientSender.getId());
imMessage.setContent(content);
imMessage.setWithdraw(false);
imMessage.setEvent(false);
imMessage.setSystem(false);
imMessage.setSendStatus(2);
imMessage.setFkConversationId(toConversationId);
imMessageService.save(imMessage);
// 封装响应的实体 // 封装响应的实体
ImMessageOnlineSend imMessageOnlineSend = new ImMessageOnlineSend(); ImMessageOnlineSend imMessageOnlineSend = new ImMessageOnlineSend();
...@@ -218,14 +184,73 @@ public class ImConcreteReceiveStrategy extends AbstractReceiveStrategy { ...@@ -218,14 +184,73 @@ public class ImConcreteReceiveStrategy extends AbstractReceiveStrategy {
responseModel.setCmd(ResponseModel.RES); responseModel.setCmd(ResponseModel.RES);
responseModel.setCode(result.getCode()); responseModel.setCode(result.getCode());
responseModel.setMsg(result.getMessage()); responseModel.setMsg(result.getMessage());
HashMap<String, Long> stringHashMap = new HashMap<>(3);
stringHashMap.put(MSG_ID, messageId);
responseModel.setData(stringHashMap);
responseModel.setReqId(receiveModel.getReqId());
// ws下发
writeDataService.write(responseModel, appKey, clientUniId);
}
HashMap<String, Long> stringHashMap = new HashMap<>(); private ImClient getClientSender(String clientUniId, ImApplication imApplication) {
stringHashMap.put("msgId", messageId); ImClient imClientSender = imClientService.getOne(new QueryWrapper<ImClient>().lambda()
.eq(ImClient::getFkAppid, imApplication.getId())
.eq(ImClient::getClientId, clientUniId));
if (imClientSender == null) {
log.error("imClientSender为空");
return null;
}
return imClientSender;
}
responseModel.setData(stringHashMap); private ImMessage saveImMessage(ImApplication imApplication, ImClient imClientSender, Long toConversationId, long messageId, String content) {
ImMessage imMessage = new ImMessage();
imMessage.setId(messageId);
imMessage.setCreateTime(new Date());
imMessage.setFkAppid(imApplication.getId());
imMessage.setSender(imClientSender.getId());
imMessage.setContent(content);
imMessage.setWithdraw(false);
imMessage.setEvent(false);
imMessage.setSystem(false);
imMessage.setSendStatus(2);
imMessage.setFkConversationId(toConversationId);
imMessageService.save(imMessage);
return imMessage;
}
private boolean black(ReceiveModel receiveModel, String appKey, String clientUniId, ImClient imClientSender, List<ImConversationMembers> membersList) {
// 判断是否被拉黑
boolean beBlack = imClientBlacklistService.isBeBlack(membersList.get(0).getFkClientId(), imClientSender.getId());
if (beBlack) {
log.debug("被对方拉黑了");
// 响应发送方
ResponseModel<HashMap<String, Long>> responseModel = new ResponseModel<>();
ApiResult<Boolean> result = ApiResult.result(ApiCode.IS_BE_BLACK);
responseModel.setCmd(ResponseModel.RES);
responseModel.setCode(result.getCode());
responseModel.setMsg(result.getMessage());
responseModel.setReqId(receiveModel.getReqId()); responseModel.setReqId(receiveModel.getReqId());
writeDataService.write(responseModel, appKey, clientUniId); writeDataService.write(responseModel, appKey, clientUniId);
return true;
}
// 是否把对方拉黑
boolean black = imClientBlacklistService.isBeBlack(imClientSender.getId(), membersList.get(0).getFkClientId());
if (black) {
log.debug("你把对方拉黑了");
// 响应发送方
ResponseModel<HashMap<String, Long>> responseModel = new ResponseModel<>();
ApiResult<Boolean> result = ApiResult.result(ApiCode.IS_TO_BLACK);
responseModel.setCmd(ResponseModel.RES);
responseModel.setCode(result.getCode());
responseModel.setMsg(result.getMessage());
responseModel.setReqId(receiveModel.getReqId());
writeDataService.write(responseModel, appKey, clientUniId);
return true;
}
return false;
} }
......
...@@ -6,7 +6,7 @@ import java.security.Key; ...@@ -6,7 +6,7 @@ import java.security.Key;
public class EncrypDES { public class EncrypDES {
// 字符串默认键值 // 字符串默认键值
private static final String strDefaultKey = "inventec2020@#$%^&"; private static final String STR_DEFAULT_KEY = "inventec2020@#$%^&";
//加密工具 //加密工具
...@@ -19,7 +19,7 @@ public class EncrypDES { ...@@ -19,7 +19,7 @@ public class EncrypDES {
* 默认构造方法,使用默认密钥 * 默认构造方法,使用默认密钥
*/ */
public EncrypDES() throws Exception { public EncrypDES() throws Exception {
this(strDefaultKey); this(STR_DEFAULT_KEY);
} }
/** /**
......
...@@ -6,7 +6,7 @@ public class RSAGenerator { ...@@ -6,7 +6,7 @@ public class RSAGenerator {
private final static String[] chars = new String[]{"a", "b", "c", "d", "e", "f", private final static String[] CHARS = new String[]{"a", "b", "c", "d", "e", "f",
"g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s",
"t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5", "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5",
"6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I",
...@@ -21,7 +21,7 @@ public class RSAGenerator { ...@@ -21,7 +21,7 @@ public class RSAGenerator {
for (int i = 0; i < 16; i++) { for (int i = 0; i < 16; i++) {
String str = uuid.substring(i * 2, i * 2 + 2); String str = uuid.substring(i * 2, i * 2 + 2);
int x = Integer.parseInt(str, 16); int x = Integer.parseInt(str, 16);
shortBuffer.append(chars[x % 0x3E]); shortBuffer.append(CHARS[x % 0x3E]);
} }
return shortBuffer.toString(); return shortBuffer.toString();
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment