Commit 7f50a93b by giaogiao

优化代码结构

parent c0ba524d
......@@ -14,21 +14,21 @@ import org.springframework.stereotype.Component;
@Slf4j
public class NettyStart {
private final NettyChannelInitializer nettyChannelInitializer;
private static final EventLoopGroup boss = new NioEventLoopGroup(1);
private static final EventLoopGroup work = new NioEventLoopGroup();
private static final ServerBootstrap serverBootstrap = new ServerBootstrap();
private static final EventLoopGroup BOSS = new NioEventLoopGroup(1);
private static final EventLoopGroup WORK = new NioEventLoopGroup();
private static final ServerBootstrap SERVER_BOOTSTRAP = new ServerBootstrap();
static {
serverBootstrap.group(boss, work);
SERVER_BOOTSTRAP.group(BOSS, WORK);
//Netty4使用对象池,重用缓冲区
serverBootstrap.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
serverBootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
SERVER_BOOTSTRAP.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
SERVER_BOOTSTRAP.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
//设置 心跳保活 socket 的参数选项 keepAlive
serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
SERVER_BOOTSTRAP.childOption(ChannelOption.SO_KEEPALIVE, true);
// 设置不延迟发送TCP_NODELAY=true
serverBootstrap.childOption(ChannelOption.TCP_NODELAY, true);
SERVER_BOOTSTRAP.childOption(ChannelOption.TCP_NODELAY, true);
// // 初始化服务端可连接队列
// serverBootstrap.option(ChannelOption.SO_BACKLOG, 1000);
......@@ -39,7 +39,7 @@ public class NettyStart {
// serverBootstrap.option(ChannelOption.SO_SNDBUF, 256 * 1024);
// 配置io模型为nio非阻塞
serverBootstrap.channel(NioServerSocketChannel.class);
SERVER_BOOTSTRAP.channel(NioServerSocketChannel.class);
}
......@@ -58,16 +58,16 @@ public class NettyStart {
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();
} catch (Exception e) {
e.printStackTrace();
} finally {
//关闭EventLoopGroup,释放掉所有资源包括创建的线程
boss.shutdownGracefully();
work.shutdownGracefully();
BOSS.shutdownGracefully();
WORK.shutdownGracefully();
}
}
......
......@@ -85,7 +85,7 @@ public class PushClient {
// Decode response string and get file_id from it
JSONObject respJson = new JSONObject(result.toString());
String ret = respJson.getString("ret");
if (!ret.equals("SUCCESS")) {
if (!"SUCCESS".equals(ret)) {
throw new Exception("Failed to upload file");
}
JSONObject data = respJson.getJSONObject("data");
......
......@@ -101,8 +101,7 @@ public class ImClientLoginServiceImpl implements ImClientLoginService {
// 保存redis
// redisTemplate.opsForValue().set("client:" + imApplication.getAppKey() + ":" + imTokenVerify.getClientId(), generateToken);
JwtToken jwtToken = new JwtToken()
.build(generateToken, secret, jwtProperties.getExpireSecond(), imClient.getClientId(), imTokenVerify.getAppKey());
JwtToken jwtToken = JwtToken.build(generateToken, secret, jwtProperties.getExpireSecond(), imClient.getClientId(), imTokenVerify.getAppKey());
appLoginRedisService.cacheLoginInfo(jwtToken);
......
......@@ -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) {
// 遍历消息id集合
for (Long MsgId : msgIds) {
for (Long msgId : msgIds) {
// 查询该消息
ImMessage imMessageDb = imMessageService.getById(MsgId);
ImMessage imMessageDb = imMessageService.getById(msgId);
// 根据会话id查询该会话所有成员
List<ImConversationMembers> membersList = imConversationMembersService.list(
......@@ -165,7 +165,7 @@ public class ImInboxServiceImpl extends BaseServiceImpl<ImInboxMapper, ImInbox>
// 消息实体
ImMessage imMessage = new ImMessage();
imMessage.setId(MsgId);
imMessage.setId(msgId);
imMessage.setCreateTime(new Date());
imMessage.setFkAppid(curentClient.getFkAppid());
imMessage.setSender(curentClient.getId());
......
......@@ -103,8 +103,7 @@ public class ImMessageServiceImpl extends BaseServiceImpl<ImMessageMapper, ImMes
return ApiResult.fail();
}
boolean isOK = this.updateById(imMessage);
if (isOK) {
if (this.updateById(imMessage)) {
return ApiResult.ok();
} else {
return ApiResult.fail();
......
......@@ -20,12 +20,12 @@ public class ResponseModel<T> implements Serializable {
public static final Integer ONLINE_EVENT_MSG = 3;
/**
* 下发在线消息
* 下发在线基本类型消息
*/
public static final Integer ONLINE_MSG = 2;
/**
* 响应数据
* 响应数据类型
*/
public static final Integer RES = 1;
......
......@@ -44,6 +44,10 @@ import java.util.List;
@Slf4j
public class ImConcreteReceiveStrategy extends AbstractReceiveStrategy {
private static final String TO_CONVERSATION_KEY = "toConversation";
private static final String MSG_ID = "msgId";
@Autowired
private ImClientBlacklistService imClientBlacklistService;
......@@ -82,24 +86,21 @@ public class ImConcreteReceiveStrategy extends AbstractReceiveStrategy {
}
// 查询发送者client
ImClient imClientSender = imClientService.getOne(new QueryWrapper<ImClient>().lambda()
.eq(ImClient::getFkAppid, imApplication.getId())
.eq(ImClient::getClientId, clientUniId));
ImClient imClientSender = getClientSender(clientUniId, imApplication);
if (imClientSender == null) {
log.error("imClientSender为空");
return;
}
JsonMapper jsonMapper = new JsonMapper();
// 获取会话id
Long toConversationId = Long.valueOf(receiveModel.getData().get("toConversation").toString());
receiveModel.getData().remove("toConversation");
if (receiveModel.getData().get(TO_CONVERSATION_KEY) == null) {
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;
JsonMapper jsonMapper = new JsonMapper();
try {
content = jsonMapper.writeValueAsString(receiveModel.getData());
} catch (JsonProcessingException e) {
......@@ -120,52 +121,17 @@ public class ImConcreteReceiveStrategy extends AbstractReceiveStrategy {
// 判断为单聊
if (membersList.size() == 1) {
// 判断是否被拉黑
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());
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);
// 拉黑逻辑
if (black(receiveModel, appKey, clientUniId, imClientSender, membersList)) {
return;
}
}
// 保存消息
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);
// 生成消息id
long messageId = SnowflakeUtil.getId();
// 保存消息至消息表
ImMessage imMessage = saveImMessage(imApplication, imClientSender, toConversationId, messageId, content);
// 封装响应的实体
ImMessageOnlineSend imMessageOnlineSend = new ImMessageOnlineSend();
......@@ -218,14 +184,73 @@ public class ImConcreteReceiveStrategy extends AbstractReceiveStrategy {
responseModel.setCmd(ResponseModel.RES);
responseModel.setCode(result.getCode());
responseModel.setMsg(result.getMessage());
HashMap<String, Long> stringHashMap = new HashMap<>();
stringHashMap.put("msgId", messageId);
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);
}
private ImClient getClientSender(String clientUniId, ImApplication imApplication) {
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;
}
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());
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;
public class EncrypDES {
// 字符串默认键值
private static final String strDefaultKey = "inventec2020@#$%^&";
private static final String STR_DEFAULT_KEY = "inventec2020@#$%^&";
//加密工具
......@@ -19,7 +19,7 @@ public class EncrypDES {
* 默认构造方法,使用默认密钥
*/
public EncrypDES() throws Exception {
this(strDefaultKey);
this(STR_DEFAULT_KEY);
}
/**
......
......@@ -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",
"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",
......@@ -21,7 +21,7 @@ public class RSAGenerator {
for (int i = 0; i < 16; i++) {
String str = uuid.substring(i * 2, i * 2 + 2);
int x = Integer.parseInt(str, 16);
shortBuffer.append(chars[x % 0x3E]);
shortBuffer.append(CHARS[x % 0x3E]);
}
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