Przeglądaj źródła

更改未读消息入库逻辑.redis只存未读消息,mysql只存已读消息

nnkwrik 6 lat temu
rodzic
commit
7e08d2fa1e

+ 7 - 8
im-service/src/main/java/io/github/nnkwrik/imservice/controller/ChatController.java

@@ -71,7 +71,6 @@ public class ChatController {
                                           @RequestParam(value = "size", defaultValue = "10") int size,
                                           @RequestParam(value = "offset", defaultValue = "0") int offset) {
         //offset,在聊天框的时候收到的消息个数
-        flushUnread(chatId, user);
         ChatForm vo = formService.showForm(chatId, user.getOpenId(), page, size, offset);
         log.info("用户openId={}获取与用户openId={}的聊天记录,展示 {} 条记录", user.getOpenId(), vo.getOtherSide().getOpenId(), vo.getHistoryList().size());
 
@@ -79,12 +78,12 @@ public class ChatController {
     }
 
     //把所有未读设为已读, 在退出聊天框时使用
-    @GetMapping("/chat/flushUnread/{chatId}")
-    public Response flushUnread(@PathVariable("chatId") int chatId,
-                                @JWT(required = true) JWTUser user) {
-        redisClient.hdel(user.getOpenId(), chatId + "");
-        log.info("用户openId={}chatId={}的所有未读消息设为已读", user.getOpenId(), chatId);
-        return Response.ok();
-    }
+//    @PostMapping("/chat/flushUnread/{chatId}")
+//    public Response flushUnread(@PathVariable("chatId") int chatId,
+//                                @JWT(required = true) JWTUser user) {
+//        formService.flushUnread(user.getOpenId(), chatId );
+//        log.info("用户openId={}chatId={}的所有未读消息设为已读", user.getOpenId(), chatId);
+//        return Response.ok();
+//    }
 
 }

+ 40 - 1
im-service/src/main/java/io/github/nnkwrik/imservice/service/impl/FormServiceImpl.java

@@ -7,11 +7,16 @@ import io.github.nnkwrik.imservice.dao.ChatMapper;
 import io.github.nnkwrik.imservice.dao.HistoryMapper;
 import io.github.nnkwrik.imservice.model.po.Chat;
 import io.github.nnkwrik.imservice.model.po.History;
+import io.github.nnkwrik.imservice.model.po.LastChat;
 import io.github.nnkwrik.imservice.model.vo.ChatForm;
+import io.github.nnkwrik.imservice.model.vo.WsMessage;
+import io.github.nnkwrik.imservice.redis.RedisClient;
 import io.github.nnkwrik.imservice.service.FormService;
 import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.BeanUtils;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
 
 import java.util.List;
 
@@ -36,14 +41,17 @@ public class FormServiceImpl implements FormService {
     @Autowired
     private GoodsClientHandler goodsClientHandler;
 
+    @Autowired
+    private RedisClient redisClient;
+
 
     @Override
     public ChatForm showForm(int chatId, String userId, int page, int size, int offset) {
+        flushUnread(userId, chatId);
         ChatForm vo = new ChatForm();
 
         Chat chat = chatMapper.getChatById(chatId);
 
-        //TODO 异步调用拿future
         if (chat.getU1().equals(userId)) {
             vo.setOtherSide(userClientHandler.getSimpleUser(chat.getU2()));
             vo.setIsU1(true);
@@ -62,5 +70,36 @@ public class FormServiceImpl implements FormService {
         return vo;
     }
 
+    private void flushUnread(String userId, int chatId) {
+        LastChat lastChat = redisClient.hget(userId, chatId + "");
+        addMessageToSQL(lastChat.getLastMsg());
+        redisClient.hdel(userId, chatId + "");
+    }
+
+//    public void flushWsMsgList(String userId, int chatId,List<WsMessage> wsMsgList){
+//
+//    }
+
+    @Transactional
+    public void addMessageToSQL(WsMessage message) {
+        String u1 = null;
+        String u2 = null;
+        if (message.getSenderId().compareTo(message.getReceiverId()) > 0) {
+            u1 = message.getReceiverId();
+            u2 = message.getSenderId();
+        } else {
+            u1 = message.getSenderId();
+            u2 = message.getReceiverId();
+        }
+
+
+        //添加聊天记录
+        History history = new History();
+        BeanUtils.copyProperties(message, history);
+        boolean u1ToU2 = u1.equals(message.getSendTime()) ? true : false;
+        history.setU1ToU2(u1ToU2);
+        historyMapper.addHistory(history);
+    }
+
 
 }

+ 1 - 0
im-service/src/main/java/io/github/nnkwrik/imservice/service/impl/IndexServiceImpl.java

@@ -68,6 +68,7 @@ public class IndexServiceImpl implements IndexService {
             List<LastChat> unread = getDisplayUnread(unreadMessage, alreadyShow, size);
             dealUnread(unread, resultVoList, chatGoodsMap, chatUserMap);
 
+
             List<Integer> unreadChatIds = unread.stream()
                     .map(chat -> chat.getLastMsg().getChatId())
                     .collect(Collectors.toList());

+ 6 - 32
im-service/src/main/java/io/github/nnkwrik/imservice/service/impl/WebSocketServiceImpl.java

@@ -5,18 +5,14 @@ import io.github.nnkwrik.common.exception.GlobalException;
 import io.github.nnkwrik.common.util.JsonUtil;
 import io.github.nnkwrik.imservice.constant.MessageType;
 import io.github.nnkwrik.imservice.dao.ChatMapper;
-import io.github.nnkwrik.imservice.dao.HistoryMapper;
-import io.github.nnkwrik.imservice.model.po.History;
 import io.github.nnkwrik.imservice.model.po.LastChat;
 import io.github.nnkwrik.imservice.model.vo.WsMessage;
 import io.github.nnkwrik.imservice.redis.RedisClient;
 import io.github.nnkwrik.imservice.service.WebSocketService;
 import io.github.nnkwrik.imservice.websocket.ChatEndpoint;
 import lombok.extern.slf4j.Slf4j;
-import org.springframework.beans.BeanUtils;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;
-import org.springframework.transaction.annotation.Transactional;
 import org.springframework.util.ObjectUtils;
 import org.springframework.util.StringUtils;
 
@@ -35,9 +31,6 @@ public class WebSocketServiceImpl implements WebSocketService {
     @Autowired
     private ChatMapper chatMapper;
 
-    @Autowired
-    private HistoryMapper historyMapper;
-
     @Autowired
     private RedisClient redisClient;
 
@@ -60,7 +53,6 @@ public class WebSocketServiceImpl implements WebSocketService {
 
         //更新数据库
         try {
-            updateSQL(message);
             updateRedis(message);
         } catch (Exception e) {
             String msg = "添加聊天记录时发生异常,消息发送失败";
@@ -70,10 +62,16 @@ public class WebSocketServiceImpl implements WebSocketService {
             return;
         }
 
+        if (message.getMessageType() == MessageType.ESTABLISH_CHAT) {
+            //首次发送,设为双方可见
+            chatMapper.showToBoth(message.getChatId());
+        }
+
         //如果接收方在线,转发ws消息到接收方
         if (chatEndpoint.hasConnect(message.getReceiverId())) {
             chatEndpoint.sendMessage(message.getReceiverId(), Response.ok(message));
         }
+
     }
 
     private void updateRedis(WsMessage message) {
@@ -89,30 +87,6 @@ public class WebSocketServiceImpl implements WebSocketService {
         redisClient.hset(message.getReceiverId(), message.getChatId() + "", lastChat);
     }
 
-    @Transactional
-    public void updateSQL(WsMessage message) throws Exception {
-        String u1 = null;
-        String u2 = null;
-        if (message.getSenderId().compareTo(message.getReceiverId()) > 0) {
-            u1 = message.getReceiverId();
-            u2 = message.getSenderId();
-        } else {
-            u1 = message.getSenderId();
-            u2 = message.getReceiverId();
-        }
-
-        if (message.getMessageType() == MessageType.ESTABLISH_CHAT) {
-            //首次发送,设为双方可见
-            chatMapper.showToBoth(message.getChatId());
-        }
-
-        //添加聊天记录
-        History history = new History();
-        BeanUtils.copyProperties(message, history);
-        boolean u1ToU2 = u1.equals(message.getSendTime()) ? true : false;
-        history.setU1ToU2(u1ToU2);
-        historyMapper.addHistory(history);
-    }
 
     private WsMessage createWsMessage(String rawData) throws GlobalException {
         WsMessage wsMessage = JsonUtil.fromJson(rawData, WsMessage.class);

+ 8 - 7
im-service/src/main/java/io/github/nnkwrik/imservice/websocket/ChatEndpoint.java

@@ -40,14 +40,15 @@ public class ChatEndpoint {
         String token = (String) config.getUserProperties().get(JWTUser.class.getName());
         JWTUser user = solveToken(token);
 
-        if (user == null || !user.getOpenId().equals(openId)) {
-            log.info("【websocket消息】token检验失败,拒绝连接, openId = [{}]", openId);
-            rejectConnect(session);
-            session.close();
-            return;
-        }
+//        if (user == null || !user.getOpenId().equals(openId)) {
+//            log.info("【websocket消息】token检验失败,拒绝连接, openId = [{}]", openId);
+//            rejectConnect(session);
+//            session.close();
+//            return;
+//        }
         sessionMap.put(openId, session);
-        log.info("【websocket消息】有新的连接, openId = [{}],用户昵称= [{}]", openId, user.getNickName());
+//        log.info("【websocket消息】有新的连接, openId = [{}],用户昵称= [{}]", openId, user.getNickName());
+        log.info("【websocket消息】有新的连接, openId = [{}],用户昵称= [{}]", openId);
 
     }