Service 业务实现层 ChatServiceImpl
核心业务处理包含会话防并发创建、消息事务入库、WebSocket推送、离线消息补发、批量已读标记。package com.para.system.chat.service.impl;import com.para.common.utils.SecurityUtils;import com.para.system.chat.domain.ChatMessage;import com.para.system.chat.domain.ChatSession;import com.para.system.chat.domain.ChatMsgDTO;import com.para.system.chat.mapper.ChatMessageMapper;import com.para.system.chat.mapper.ChatSessionMapper;import com.para.system.chat.service.ChatService;import com.para.system.chat.websocket.ChatWebSocketServer;import lombok.extern.slf4j.Slf4j;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;import javax.annotation.Resource;import java.util.Date;import java.util.List;import java.util.Set;import java.util.stream.Collectors;/**聊天业务实现类功能会话管理、消息存储、未读计数、消息推送、离线消息补发*/Slf4jServicepublic class ChatServiceImpl implements ChatService {Resourceprivate ChatSessionMapper sessionMapper;Resourceprivate ChatMessageMapper msgMapper;/**获取或创建两个用户之间的聊天会话防并发重复创建param fromUid 当前登录用户IDparam toUid 对方用户IDreturn 会话对象*/Overridepublic ChatSession getOrCreateSession(Long fromUid, Long toUid) {// 禁止自己和自己聊天if (fromUid.equals(toUid)) {throw new RuntimeException(“不允许与自己创建聊天会话”);}// 统一大小ID存储保证双人会话唯一Long minId Math.min(fromUid, toUid);Long maxId Math.max(fromUid, toUid);Long loginUid SecurityUtils.getLoginUser().getUserId();// 查询已有会话ChatSession session sessionMapper.selectByUserPair(minId, maxId, loginUid);if (session null) {try {session new ChatSession();session.setFromUserId(minId);session.setToUserId(maxId);sessionMapper.insertSession(session);} catch (Exception e) {// 唯一索引冲突其他线程已创建日志告警不抛出异常log.warn(“会话创建冲突重新查询会话记录”);}// 冲突后二次查询返回最新会话return sessionMapper.selectByUserPair(minId, maxId, loginUid);}return session;}/**保存消息并异步推送给接收方数据库操作在事务内WebSocket推送在事务外避免长连接阻塞事务*/Overridepublic void saveAndPushMessage(Long senderId, ChatMsgDTO dto) {Long receiverId dto.getReceiverId();// 事务入库、更新会话、未读数1saveMessageInTransaction(senderId, dto);// 事务外推送消息推送失败不影响消息存储try {ChatWebSocketServer.sendToUser(receiverId, dto);} catch (Exception e) {log.error(“WebSocket推送消息失败发送人:{},接收人:{}”, senderId, receiverId, e);}}/**事务方法保存消息、更新会话最后消息、未读数自增*/Transactional(rollbackFor Exception.class)public void saveMessageInTransaction(Long senderId, ChatMsgDTO dto) {Long sessionId dto.getSessionId();Long receiverId dto.getReceiverId();Date now new Date();// 1. 插入聊天消息默认未读0ChatMessage msg new ChatMessage();msg.setSessionId(sessionId);msg.setSenderId(senderId);msg.setReceiverId(receiverId);msg.setContent(dto.getContent());msg.setMsgType(dto.getMsgType());msg.setReadStatus(“0”);msg.setCreateTime(now);msgMapper.insert(msg);// 2. 更新会话最后一条消息内容和时间sessionMapper.updateLastMsg(sessionId, dto.getContent(), now);// 3. 当前会话未读计数1sessionMapper.incrUnread(sessionId);}/**查询会话分页历史消息*/Overridepublic List history(Long sessionId) {return msgMapper.selectBySession(sessionId);}/**查询当前用户会话列表支持对方昵称模糊检索*/Overridepublic List sessionList(Long uid, String nickName) {return sessionMapper.selectUserSessions(uid, nickName);}/**批量标记会话全部消息已读清空会话未读计数*/OverrideTransactionalpublic void markAllRead(Long sessionId, Long uid) {msgMapper.batchRead(sessionId, uid);sessionMapper.clearUnread(sessionId);}/**用户WebSocket上线补发所有离线未读消息*/Overridepublic void pushOfflineMessage(Long uid) {List unreadList msgMapper.selectUnread(uid);if (unreadList null || unreadList.isEmpty()) {return;}// 逐条推送离线消息for (ChatMessage msg : unreadList) {ChatMsgDTO dto new ChatMsgDTO();dto.setSessionId(msg.getSessionId());dto.setReceiverId(msg.getReceiverId());dto.setContent(msg.getContent());dto.setMsgType(msg.getMsgType());ChatWebSocketServer.sendToUser(uid, dto);}// 推送完成批量标记已读避免重复推送try {Set sessionIds unreadList.stream().map(ChatMessage::getSessionId).collect(Collectors.toSet());for (Long sessionId : sessionIds) {msgMapper.batchRead(sessionId, uid);sessionMapper.clearUnread(sessionId);}} catch (Exception e) {log.error(“离线消息标记已读失败”, e);}}}5.3 Mapper 接口补充ChatSessionMapper.javapackage com.para.system.chat.mapper;import com.para.system.chat.domain.ChatSession;import org.apache.ibatis.annotations.Param;import java.util.List;public interface ChatSessionMapper {ChatSession selectByUserPair(Param(from) Long minId, Param(to) Long maxId, Param(uid) Long loginUid); void insertSession(ChatSession session); void updateLastMsg(Param(sid) Long sessionId, Param(content) String content, Param(time) java.util.Date time); void incrUnread(Param(sid) Long sessionId); void clearUnread(Param(sid) Long sessionId); ListChatSession selectUserSessions(Param(uid) Long uid, Param(nickName) String nickName);}ChatMessageMapper.javapackage com.para.system.chat.mapper;import com.para.system.chat.domain.ChatMessage;import org.apache.ibatis.annotations.Param;import java.util.List;public interface ChatMessageMapper {void insert(ChatMessage message); ListChatMessage selectBySession(Param(sessionId) Long sessionId); void batchRead(Param(sessionId) Long sessionId, Param(uid) Long userId); ListChatMessage selectUnread(Param(uid) Long userId);}5.4 MyBatis Mapper XML ChatSessionMapper.xml核心复杂SQL联表用户获取昵称头像、子查询实时统计未读、昵称模糊搜索、双人会话唯一查询。?xml version1.0 encodingUTF-8?!-- 会话结果映射关联用户昵称、头像、实时未读数量 -- resultMap typecom.para.system.chat.domain.ChatSession idChatSessionResult result propertyid columnid / result propertyfromUserId columnfrom_user_id / result propertytoUserId columnto_user_id / result propertylastContent columnlast_content / result propertylastMsgTime columnlast_msg_time / result propertyunreadCount columnunread_count / result propertyrealSelfUnread columnreal_self_unread/ result propertycreateTime columncreate_time / result propertyupdateTime columnupdate_time / result columnnick_name propertytargetNickName/ result columnavatar propertytargetAvatar/ /resultMap !-- 根据双方用户ID查询唯一会话关联用户信息实时未读统计 -- select idselectByUserPair resultMapChatSessionResult SELECT cs.*, su.nick_name, su.avatar, COALESCE(cm.unread_total,0) AS real_self_unread FROM chat_session cs LEFT JOIN sys_user su ON su.user_id ( CASE WHEN cs.from_user_id #{uid} THEN cs.to_user_id ELSE cs.from_user_id END ) LEFT JOIN ( SELECT session_id, COUNT(1) unread_total FROM chat_message WHERE receiver_id #{uid} AND read_status 0 GROUP BY session_id ) cm ON cs.id cm.session_id WHERE (from_user_id #{from} AND to_user_id #{to}) OR (from_user_id #{to} AND to_user_id #{from}) LIMIT 1 /select !-- 新增双人会话 -- insert idinsertSession parameterTypeChatSession INSERT INTO chat_session ( from_user_id, to_user_id, last_content, last_msg_time, unread_count, create_time, update_time ) VALUES ( #{fromUserId}, #{toUserId}, #{lastContent}, #{lastMsgTime}, #{unreadCount}, sysdate(), sysdate() ) /insert !-- 更新会话最后一条消息内容和时间 -- update idupdateLastMsg UPDATE chat_session SET last_content #{content}, last_msg_time #{time}, update_time sysdate() WHERE id #{sid} /update !-- 会话未读计数 1 -- update idincrUnread UPDATE chat_session SET unread_count unread_count 1, update_time sysdate() WHERE id #{sid} /update !-- 清空会话未读计数 -- update idclearUnread

相关新闻

【讯飞AI开发者大赛_学习笔记】

【讯飞AI开发者大赛_学习笔记】

2026/7/28 1:10:16 阅读更多 →
GetQzonehistory:如何快速找回QQ空间全部历史说说的终极完整指南

GetQzonehistory:如何快速找回QQ空间全部历史说说的终极完整指南

GetQzonehistory:如何快速找回QQ空间全部历史说说的终极完整指南 【免费下载链接】GetQzonehistory 获取QQ空间发布的历史说说 项目地址: https://gitcode.com/GitHub_Trending/ge/GetQzonehistory 你是否曾试图找回QQ空间中那些被时间淹没的青春记忆&#x…

2026/7/26 22:39:38 阅读更多 →
抖音自动化视频发布工具:告别重复劳动,专注内容创作

抖音自动化视频发布工具:告别重复劳动,专注内容创作

抖音自动化视频发布工具:告别重复劳动,专注内容创作 【免费下载链接】douyin_uplod 抖音自动上传发布视频 项目地址: https://gitcode.com/gh_mirrors/do/douyin_uplod 在当今短视频内容爆发的时代,抖音创作者面临着前所未有的挑战&am…

2026/7/27 15:20:17 阅读更多 →

最新新闻

AngularEditor自定义按钮开发指南:构建专属编辑工具的终极方案

AngularEditor自定义按钮开发指南:构建专属编辑工具的终极方案

AngularEditor自定义按钮开发指南:构建专属编辑工具的终极方案 【免费下载链接】angular-editor A simple native WYSIWYG editor component for Angular 6 -20 项目地址: https://gitcode.com/gh_mirrors/ang/angular-editor AngularEditor是一款专为Angula…

2026/7/28 8:40:06 阅读更多 →
鸿蒙三方库 | harmony-utils之DateUtil日期比较与判断详解

鸿蒙三方库 | harmony-utils之DateUtil日期比较与判断详解

前言 日期比较和判断在日程管理、倒计时、有效期检查等场景中广泛使用。pura/harmony-utils 的 DateUtil 封装了日期比较和判断方法。本文将从API说明、代码实战、进阶用法、常见问题等多个维度进行全面讲解,帮助开发者快速掌握并应用到实际项目中。一、DateUtil比较…

2026/7/28 8:40:06 阅读更多 →
AzurLaneAutoScript技术架构解析:构建高效碧蓝航线自动化系统的完整指南

AzurLaneAutoScript技术架构解析:构建高效碧蓝航线自动化系统的完整指南

AzurLaneAutoScript技术架构解析:构建高效碧蓝航线自动化系统的完整指南 【免费下载链接】AzurLaneAutoScript Azur Lane bot (CN/EN/JP/TW) 碧蓝航线脚本 | 无缝委托科研,全自动大世界 项目地址: https://gitcode.com/gh_mirrors/az/AzurLaneAutoScri…

2026/7/28 8:40:06 阅读更多 →
苹果触控板Windows驱动终极指南:5分钟实现原生级触控体验

苹果触控板Windows驱动终极指南:5分钟实现原生级触控体验

苹果触控板Windows驱动终极指南:5分钟实现原生级触控体验 【免费下载链接】mac-precision-touchpad Windows Precision Touchpad Driver Implementation for Apple MacBook / Magic Trackpad 项目地址: https://gitcode.com/gh_mirrors/ma/mac-precision-touchpad…

2026/7/28 8:40:06 阅读更多 →
二分查找算法原理、实现与优化全解析

二分查找算法原理、实现与优化全解析

1. 二分查找算法核心原理剖析 二分查找(Binary Search)作为计算机科学中最基础且高效的搜索算法之一,其核心思想源于分治策略。这个看似简单的算法在实际应用中却蕴含着精妙的设计哲学——每次比较都将搜索范围减半,使得时间复杂度…

2026/7/28 8:40:06 阅读更多 →
玻尔兹曼机光谱数据处理实战:细菌拉曼光谱上的RBM少标签分类

玻尔兹曼机光谱数据处理实战:细菌拉曼光谱上的RBM少标签分类

本文是一篇“光谱数据处理 + 受限玻尔兹曼机(Restricted Boltzmann Machine, RBM)”的实战讲解稿。它不重新运行你的脚本,而是基于你提供的真实结果文件、脚本和 5 张图,把整条链路从零讲清楚:数据是什么、为什么要这样预处理、RBM 到底学到了什么、少标签实验为什么这样设…

2026/7/28 8:39:06 阅读更多 →

日新闻

告别臃肿!3步让你的暗影精灵笔记本重获新生

告别臃肿!3步让你的暗影精灵笔记本重获新生

告别臃肿!3步让你的暗影精灵笔记本重获新生 【免费下载链接】OmenSuperHub Control Omen laptop performance, fan speeds, and keyboard lighting, and unlock power limits. 项目地址: https://gitcode.com/gh_mirrors/om/OmenSuperHub 你是否也曾为官方Om…

2026/7/28 0:00:43 阅读更多 →
RAG必踩坑!财报法规检索不准?这款开源工具让答案浮出水面,准确率飙升98.7%!

RAG必踩坑!财报法规检索不准?这款开源工具让答案浮出水面,准确率飙升98.7%!

做 RAG 的人应该都踩过这个致命的坑:把几百页的财报、法规、技术手册扔给向量库,问一个具体问题,搜出来的全是沾边但没用的内容 —— 关键信息要么被硬切块拆碎了,要么藏在几十条结果的最下面。语义相似≠真正相关,这个…

2026/7/28 0:00:43 阅读更多 →
抖音视频文案提取工具全指南:免费2026版、手机App、在线工具一网打尽

抖音视频文案提取工具全指南:免费2026版、手机App、在线工具一网打尽

2026年做短视频运营,从抖音上扒文案早就不是偷偷抄笔记的事了。我刚开始做内容的时候,每天刷半小时抖音,手动把爆款视频的口播敲进备忘录,一条2分钟的视频得花十来分钟,碰到语速快的还要反复回听。后来试了一圈工具&am…

2026/7/28 0:00:43 阅读更多 →

周新闻

深度学习道路桥梁裂缝检测系统 道路桥梁裂缝检测数据集 道路桥梁病害识别检测数据集

深度学习道路桥梁裂缝检测系统 道路桥梁裂缝检测数据集 道路桥梁病害识别检测数据集

深度学习道路桥梁裂缝检测系统 数据集6000张 完整源码已标注数据集训练好的模型环境配置教程程序运行说明文档,可以直接使用!系统支持图片、视频、摄像头等多种方式检测裂缝,功能强大实用。 1数据集6000张 8各类别

2026/7/27 4:33:59 阅读更多 →
深度学习YOLO模型如何训练 PUBG 绝地求生目标检测数据集

深度学习YOLO模型如何训练 PUBG 绝地求生目标检测数据集

pubg数据集 精选原图1.42万数据 1.49万标签 无任何重复、算法增强或冗余图像! pubg绝地求生目标检测数据集 1分类:e_body,14905个标签,txt格式 共计14244张图,99%为640*640尺寸图像 适合yolo目标检测、AI训练关键词&am…

2026/7/28 8:29:16 阅读更多 →
Apex英雄目标检测数据集 深度学习框架YOLO如何训练APEX数据集

Apex英雄目标检测数据集 深度学习框架YOLO如何训练APEX数据集

Apex检测数据集数据集详情检测类别: allies enemy tag图片总量:7247张训练集:5139张验证集:1425张测试集:683张标注状态:全部已标注,即拿即用数据格式:支持YOLO格式及其他格式&#…

2026/7/28 5:03:42 阅读更多 →

月新闻