SpringBoot+WebSocket实现即时通讯(四)

前言

紧接着上文《SpringBoot+WebSocket实现即时通讯(三)》

本博客姊妹篇

  • SpringBoot+WebSocket实现即时通讯(一)
  • SpringBoot+WebSocket实现即时通讯(二)
  • SpringBoot+WebSocket实现即时通讯(三)
  • SpringBoot+WebSocket实现即时通讯(四)

一、功能描述

  • 用户管理:业务自己实现,暂从数据库添加
  • 好友管理:添加好友、删除好友、修改备注、好友列表等
  • 群组管理:新建群、解散群、编辑群、变更群主、拉人进群、踢出群等
  • 聊天模式:私聊、群聊
  • 消息类型:系统、文本、语音、图片、视频
  • 聊天管理:删除聊天、置顶聊天、查看聊天记录等

二、消息、聊天会话功能实现

2.1 消息

mapper

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.qiangesoft.im.mapper.ImMessageMapper"><select id="listMessage" resultType="com.qiangesoft.im.pojo.vo.ImMessageVO">SELECTb.id,b.sender_id,b.message_type,b.message,b.create_time,c.read_flagFROMim_chat aINNER JOIN im_message b ON a.id = b.chat_idINNER JOIN im_message_receiver c ON b.id = c.message_idWHEREa.del_flag = FALSEAND a.id = #{chatId}AND c.receiver_id = #{userId}<if test="messageType != null and messageType != ''">AND b.message_type = #{messageType}</if><if test="message != null and message != ''">AND b.message like concat('%', #{message}, '%')</if>ORDER BY b.id DESC</select><select id="listUnreadMessage" resultType="com.qiangesoft.im.pojo.vo.ImMessageVO">SELECTb.id,b.sender_id,b.message_type,b.message,b.create_time,c.read_flagFROMim_chat aINNER JOIN im_message b ON a.id = b.chat_idINNER JOIN im_message_receiver c ON b.id = c.message_idWHEREa.del_flag = FALSEAND a.id = #{chatId}AND c.receiver_id = #{userId}AND c.read_flag = FALSEORDER BY b.id DESC</select><select id="listChatUnreadMessage" resultType="com.qiangesoft.im.pojo.bo.ImChatMessageBO">SELECTa.chat_id AS chatId,COUNT(a.id) AS unreadNumFROMim_message a INNER JOINim_message_receiver b ON a.id=b.message_idWHEREb.receiver_id=#{userId}AND b.read_flag=FALSEAND a.chat_id IN<foreach collection="chatIdList" item="chatId" open="(" separator="," close=")">#{chatId}</foreach>GROUP BY a.chat_id</select><select id="listLatestMessage" resultType="com.qiangesoft.im.entity.ImMessage">SELECT * FROM im_message WHERE id IN (SELECTmax(a.id)FROMim_message a INNER JOINim_message_receiver b ON a.id=b.message_idWHEREb.receiver_id=#{userId}AND a.chat_id IN<foreach collection="chatIdList" item="chatId" open="(" separator="," close=")">#{chatId}</foreach>GROUP BY a.chat_id)</select></mapper>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.qiangesoft.im.mapper.ImMessageReceiverMapper"><update id="updateRead">UPDATE im_message_receiver aINNER JOIN im_message bON b.id = a.message_idINNER JOIN im_chat c ON c.id = b.chat_idSET read_flag = 1WHEREa.read_flag = 0AND a.receiver_id = #{userId}AND c.id = #{chatId}<if test="messageId != null">AND b.id = #{messageId}</if></update>
</mapper>
package com.qiangesoft.im.mapper;import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.qiangesoft.im.entity.ImMessage;
import com.qiangesoft.im.pojo.bo.ImChatMessageBO;
import com.qiangesoft.im.pojo.vo.ImMessageVO;
import org.apache.ibatis.annotations.Param;import java.util.List;/*** <p>* 消息 Mapper 接口* </p>** @author qiangesoft* @date 2024-02-07*/
public interface ImMessageMapper extends BaseMapper<ImMessage> {/*** 消息列表** @param page* @param userId* @param chatId* @param messageType* @param message* @return*/IPage<ImMessageVO> listMessage(@Param("page") IPage<ImMessage> page, @Param("userId") Long userId, @Param("chatId") Long chatId,@Param("messageType") String messageType, @Param("message") String message);/*** 未读消息列表** @param userId* @param chatId* @return*/List<ImMessageVO> listUnreadMessage(@Param("userId") Long userId, @Param("chatId") Long chatId);/*** 会话未读消息** @param userId* @param chatIdList* @return*/List<ImChatMessageBO> listChatUnreadMessage(@Param("userId") Long userId, @Param("chatIdList") List<Long> chatIdList);/*** 会话最新消息** @param userId* @param chatIdList* @return*/List<ImMessage> listLatestMessage(@Param("userId") Long userId, @Param("chatIdList") List<Long> chatIdList);
}
package com.qiangesoft.im.mapper;import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.qiangesoft.im.entity.ImMessageReceiver;
import org.apache.ibatis.annotations.Param;/*** <p>* 群用户消息关系 Mapper 接口* </p>** @author qiangesoft* @since 2023-08-23*/
public interface ImMessageReceiverMapper extends BaseMapper<ImMessageReceiver> {/*** 置为已读** @param userId* @param chatId* @param messageId*/void updateRead(@Param("userId") Long userId, @Param("chatId") Long chatId, @Param("messageId") Long messageId);
}

service

package com.qiangesoft.im.service;import com.baomidou.mybatisplus.extension.service.IService;
import com.qiangesoft.im.entity.ImMessage;
import com.qiangesoft.im.pojo.bo.ImChatMessageBO;
import com.qiangesoft.im.pojo.dto.ImMessageDTO;
import com.qiangesoft.im.pojo.dto.query.MessageQueryDTO;
import com.qiangesoft.im.pojo.dto.query.PageQueryDTO;
import com.qiangesoft.im.pojo.vo.ImMessageVO;
import com.qiangesoft.im.pojo.vo.PageResultVO;import java.util.List;/*** <p>* 消息 服务类* </p>** @author qiangesoft* @date 2024-02-07*/
public interface IImMessageService extends IService<ImMessage> {/*** 消息列表** @param pageQuery* @param messageQuery* @return*/PageResultVO<ImMessageVO> listMessage(PageQueryDTO pageQuery, MessageQueryDTO messageQuery);/*** 未读消息列表** @param chatId* @return*/List<ImMessageVO> listUnreadMessage(Long chatId);/*** 发送消息** @param messageDTO* @return*/ImMessage send(ImMessageDTO messageDTO);/*** 聊天未读消息** @param userId* @param chatIdList* @return*/List<ImChatMessageBO> listChatUnreadMessage(Long userId, List<Long> chatIdList);/*** 聊天最新消息** @param userId* @param chatIdList* @return*/List<ImMessage> listLatestMessage(Long userId, List<Long> chatIdList);
}
package com.qiangesoft.im.service;import com.baomidou.mybatisplus.extension.service.IService;
import com.qiangesoft.im.entity.ImMessageReceiver;/*** <p>* 群用户消息关系 服务类* </p>** @author qiangesoft* @since 2023-08-23*/
public interface IImMessageReceiverService extends IService<ImMessageReceiver> {/*** 置为已读** @param chatId* @param messageId*/void updateRead(Long chatId, Long messageId);}
package com.qiangesoft.im.service.impl;import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qiangesoft.im.auth.UserUtil;
import com.qiangesoft.im.core.constant.ChatTypeEnum;
import com.qiangesoft.im.entity.*;
import com.qiangesoft.im.exception.ServiceException;
import com.qiangesoft.im.mapper.ImMessageMapper;
import com.qiangesoft.im.pojo.bo.ImChatMessageBO;
import com.qiangesoft.im.pojo.dto.ImMessageDTO;
import com.qiangesoft.im.pojo.dto.query.MessageQueryDTO;
import com.qiangesoft.im.pojo.dto.query.PageQueryDTO;
import com.qiangesoft.im.pojo.vo.ImMessageVO;
import com.qiangesoft.im.pojo.vo.PageResultVO;
import com.qiangesoft.im.pojo.vo.SysUserVo;
import com.qiangesoft.im.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;import java.util.*;
import java.util.stream.Collectors;/*** <p>* 群消息 服务实现类* </p>** @author qiangesoft* @date 2024-02-07*/
@Service
public class ImMessageServiceImpl extends ServiceImpl<ImMessageMapper, ImMessage> implements IImMessageService {@Lazy@Autowiredprivate IImChatService chatService;@Autowiredprivate IImFriendService friendService;@Autowiredprivate IImGroupUserService groupUserService;@Autowiredprivate IImMessageReceiverService messageReceiverService;@Autowiredprivate ISysUserService sysUserService;@Overridepublic PageResultVO<ImMessageVO> listMessage(PageQueryDTO pageQuery, MessageQueryDTO messageQuery) {Long chatId = messageQuery.getChatId();ImChat chat = chatService.getById(chatId);if (chat == null) {throw new ServiceException("聊天不存在");}Long userId = UserUtil.getUserId();Integer pageNum = pageQuery.getPageNum();Integer pageSize = pageQuery.getPageSize();PageResultVO<ImMessageVO> pageResult = new PageResultVO<>();pageResult.setPageNum(pageNum);pageResult.setPageSize(pageSize);IPage<ImMessageVO> messagePage = baseMapper.listMessage(new Page<>(pageNum, pageSize), userId, messageQuery.getChatId(), messageQuery.getMessageType(), messageQuery.getMessage());pageResult.setTotal(messagePage.getTotal());pageResult.setPages(messagePage.getPages());List<ImMessageVO> records = messagePage.getRecords();if (CollectionUtils.isEmpty(records)) {pageResult.setResults(records);return pageResult;}Set<Long> senderIdList = records.stream().map(ImMessageVO::getSenderId).collect(Collectors.toSet());Long targetId = chat.getTargetId();Map<Long, String> avatarMap = sysUserService.listByIds(senderIdList).stream().collect(Collectors.toMap(SysUser::getId, SysUser::getAvatar));Map<Long, String> nickNameMap = new HashMap<>();if (ChatTypeEnum.GROUP.getCode().equals(chat.getChatType())) {LambdaQueryWrapper<ImGroupUser> queryWrapper = new LambdaQueryWrapper<>();queryWrapper.eq(ImGroupUser::getGroupId, targetId).in(ImGroupUser::getUserId, senderIdList);nickNameMap = groupUserService.list(queryWrapper).stream().collect(Collectors.toMap(ImGroupUser::getUserId, ImGroupUser::getNickName));} else {ImFriend friend = friendService.getById(targetId);nickNameMap.put(userId, UserUtil.getNickName());nickNameMap.put(targetId, friend.getRemark());}for (ImMessageVO record : records) {SysUserVo sysUserVo = new SysUserVo();Long senderId = record.getSenderId();sysUserVo.setId(senderId);sysUserVo.setAvatar(avatarMap.get(senderId));sysUserVo.setNickName(nickNameMap.get(senderId));record.setSender(sysUserVo);}pageResult.setResults(records);return pageResult;}@Overridepublic List<ImMessageVO> listUnreadMessage(Long chatId) {ImChat chat = chatService.getById(chatId);if (chat == null) {throw new ServiceException("聊天不存在");}Long userId = UserUtil.getUserId();List<ImMessageVO> records = baseMapper.listUnreadMessage(userId, chatId);if (CollectionUtils.isEmpty(records)) {return records;}Set<Long> senderIdList = records.stream().map(ImMessageVO::getSenderId).collect(Collectors.toSet());Long targetId = chat.getTargetId();Map<Long, String> avatarMap = sysUserService.listByIds(senderIdList).stream().collect(Collectors.toMap(SysUser::getId, SysUser::getAvatar));Map<Long, String> nickNameMap = new HashMap<>();if (ChatTypeEnum.GROUP.getCode().equals(chat.getChatType())) {LambdaQueryWrapper<ImGroupUser> queryWrapper = new LambdaQueryWrapper<>();queryWrapper.eq(ImGroupUser::getGroupId, targetId).in(ImGroupUser::getUserId, senderIdList);nickNameMap = groupUserService.list(queryWrapper).stream().collect(Collectors.toMap(ImGroupUser::getUserId, ImGroupUser::getNickName));} else {ImFriend friend = friendService.getById(targetId);nickNameMap.put(userId, UserUtil.getNickName());nickNameMap.put(targetId, friend.getRemark());}for (ImMessageVO record : records) {SysUserVo sysUserVo = new SysUserVo();Long senderId = record.getSenderId();sysUserVo.setId(senderId);sysUserVo.setAvatar(avatarMap.get(senderId));sysUserVo.setNickName(nickNameMap.get(senderId));record.setSender(sysUserVo);}return records;}@Transactional(rollbackFor = RuntimeException.class)@Overridepublic ImMessage send(ImMessageDTO messageDTO) {Long userId = UserUtil.getUserId();ImMessage message = null;String chatType = messageDTO.getChatType();if (ChatTypeEnum.GROUP.getCode().equals(chatType)) {message = this.sendGroupMessage(messageDTO, userId);}if (ChatTypeEnum.PERSON.getCode().equals(chatType)) {message = this.sendPersonMessage(messageDTO, userId);}return message;}/*** 私聊消息** @param messageDTO* @param userId* @return*/private ImMessage sendPersonMessage(ImMessageDTO messageDTO, Long userId) {Long friendUserId = messageDTO.getTargetId();LambdaQueryWrapper<ImFriend> queryWrapper = new LambdaQueryWrapper<>();queryWrapper.eq(ImFriend::getFriendUserId, friendUserId).eq(ImFriend::getUserId, userId).eq(ImFriend::getDelFlag, false);ImFriend friend = friendService.getOne(queryWrapper);if (friend == null) {throw new ServiceException("非好友关系");}// 聊天会话Long chatId = messageDTO.getChatId();if (chatId == null) {LambdaQueryWrapper<ImChat> queryWrapper1 = new LambdaQueryWrapper<>();queryWrapper1.eq(ImChat::getUserId, userId).eq(ImChat::getChatType, messageDTO.getChatType()).eq(ImChat::getTargetId, friendUserId).eq(ImChat::getDelFlag, false);ImChat chat = chatService.getOne(queryWrapper1);if (chat == null) {chat = new ImChat();chat.setUserId(userId);chat.setChatType(messageDTO.getChatType());chat.setTargetId(friendUserId);chat.setDelFlag(false);chatService.save(chat);}messageDTO.setChatId(chat.getId());}// 消息ImMessage message = new ImMessage();message.setSenderId(userId);message.setChatId(messageDTO.getChatId());message.setMessageType(messageDTO.getMessageType());message.setMessage(messageDTO.getMessage());message.setDelFlag(false);baseMapper.insert(message);// 发送ImMessageReceiver messageReceiver = new ImMessageReceiver();messageReceiver.setMessageId(message.getId());messageReceiver.setReceiverId(friendUserId);messageReceiver.setDelFlag(false);messageReceiver.setReadFlag(false);messageReceiverService.save(messageReceiver);return message;}/*** 群聊消息** @param messageDTO* @param userId* @return*/private ImMessage sendGroupMessage(ImMessageDTO messageDTO, Long userId) {Long groupId = messageDTO.getTargetId();LambdaQueryWrapper<ImGroupUser> queryWrapper = new LambdaQueryWrapper<>();queryWrapper.eq(ImGroupUser::getGroupId, groupId).eq(ImGroupUser::getUserId, userId).eq(ImGroupUser::getDelFlag, false);ImGroupUser imGroupUser = groupUserService.getOne(queryWrapper);if (imGroupUser == null) {throw new ServiceException("无法发言,您已不在群中");}// 聊天会话Long chatId = messageDTO.getChatId();if (chatId == null) {LambdaQueryWrapper<ImChat> queryWrapper1 = new LambdaQueryWrapper<>();queryWrapper1.eq(ImChat::getUserId, userId).eq(ImChat::getChatType, messageDTO.getChatType()).eq(ImChat::getTargetId, groupId).eq(ImChat::getDelFlag, false);ImChat chat = chatService.getOne(queryWrapper1);if (chat == null) {chat = new ImChat();chat.setUserId(userId);chat.setChatType(messageDTO.getChatType());chat.setTargetId(groupId);chat.setDelFlag(false);chatService.save(chat);}messageDTO.setChatId(chat.getId());}// 消息ImMessage message = new ImMessage();message.setSenderId(userId);message.setChatId(messageDTO.getChatId());message.setMessageType(messageDTO.getMessageType());message.setMessage(messageDTO.getMessage());message.setDelFlag(false);baseMapper.insert(message);// 发给群成员List<SysUserVo> groupUserList = groupUserService.listGroupUser(groupId);List<ImMessageReceiver> messageReceiverList = new ArrayList<>();for (SysUserVo sysUserVo : groupUserList) {ImMessageReceiver messageReceiver = new ImMessageReceiver();messageReceiver.setMessageId(message.getId());messageReceiver.setReceiverId(sysUserVo.getId());messageReceiver.setDelFlag(false);messageReceiver.setReadFlag(false);if (userId.equals(sysUserVo.getId())) {messageReceiver.setReadFlag(true);}messageReceiverList.add(messageReceiver);}messageReceiverService.saveBatch(messageReceiverList);return message;}@Overridepublic List<ImChatMessageBO> listChatUnreadMessage(Long userId, List<Long> chatIdList) {return baseMapper.listChatUnreadMessage(userId, chatIdList);}@Overridepublic List<ImMessage> listLatestMessage(Long userId, List<Long> chatIdList) {return baseMapper.listLatestMessage(userId, chatIdList);}
}
package com.qiangesoft.im.service.impl;import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qiangesoft.im.auth.UserUtil;
import com.qiangesoft.im.entity.ImMessageReceiver;
import com.qiangesoft.im.mapper.ImMessageReceiverMapper;
import com.qiangesoft.im.service.IImMessageReceiverService;
import org.springframework.stereotype.Service;/*** <p>* 群用户消息关系 服务实现类* </p>** @author qiangesoft* @since 2023-08-23*/
@Service
public class ImMessageReceiverServiceImpl extends ServiceImpl<ImMessageReceiverMapper, ImMessageReceiver> implements IImMessageReceiverService {@Overridepublic void updateRead(Long chatId, Long messageId) {baseMapper.updateRead(UserUtil.getUserId(), chatId, messageId);}
}

controller

package com.qiangesoft.im.controller;import com.qiangesoft.im.core.ImWebSocketServer;
import com.qiangesoft.im.entity.ImMessage;
import com.qiangesoft.im.pojo.bo.ImMessageBO;
import com.qiangesoft.im.pojo.dto.ImMessageDTO;
import com.qiangesoft.im.pojo.dto.ImMessageReadDTO;
import com.qiangesoft.im.pojo.dto.query.MessageQueryDTO;
import com.qiangesoft.im.pojo.dto.query.PageQueryDTO;
import com.qiangesoft.im.pojo.vo.ImMessageVO;
import com.qiangesoft.im.pojo.vo.PageResultVO;
import com.qiangesoft.im.pojo.vo.ResultInfo;
import com.qiangesoft.im.service.IImMessageReceiverService;
import com.qiangesoft.im.service.IImMessageService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;import java.util.List;/*** <p>* 群消息 前端控制器* </p>** @author qiangesoft* @date 2024-02-07*/
@Api(tags = "消息")
@RestController
@RequestMapping("/im/message")
public class ImMessageController {@Autowiredprivate IImMessageService messageService;@Autowiredprivate IImMessageReceiverService messageReceiverService;@GetMapping@ApiOperation(value = "消息列表")public ResultInfo<PageResultVO<ImMessageVO>> listMessage(@Validated PageQueryDTO pageQuery, @Validated MessageQueryDTO messageQuery) {PageResultVO<ImMessageVO> pageResult = messageService.listMessage(pageQuery, messageQuery);return ResultInfo.ok(pageResult);}@GetMapping("/unread")@ApiOperation(value = "未读消息列表")public ResultInfo<List<ImMessageVO>> listUnreadMessage(Long chatId) {List<ImMessageVO> messageList = messageService.listUnreadMessage(chatId);return ResultInfo.ok(messageList);}@PostMapping("/send")@ApiOperation(value = "发送消息")public ResultInfo<Void> send(@Validated @RequestBody ImMessageDTO messageDTO) {ImMessage message = messageService.send(messageDTO);// 发送消息ImMessageBO messageBO = new ImMessageBO();messageBO.setId(message.getId());messageBO.setSenderId(message.getSenderId());messageBO.setChatId(message.getChatId());messageBO.setMessageType(message.getMessageType());messageBO.setMessage(message.getMessage());messageBO.setSendTime(message.getCreateTime());messageBO.setChatType(messageDTO.getChatType());messageBO.setTargetId(messageDTO.getTargetId());messageBO.setExtra(messageDTO.getExtra());messageBO.setTimestamp(messageDTO.getTimestamp());ImWebSocketServer.sendMessage(messageBO);return ResultInfo.ok();}@PutMapping("/read")@ApiOperation(value = "阅读消息")public ResultInfo<Void> read(@Validated @RequestBody ImMessageReadDTO messageReadDTO) {messageReceiverService.updateRead(messageReadDTO.getChatId(), messageReadDTO.getId());return ResultInfo.ok();}
}

2.2 聊天会话

mapper

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.qiangesoft.im.mapper.ImChatMapper"><select id="listChat" resultType="com.qiangesoft.im.entity.ImChat">SELECT a.id,a.user_id,a.chat_type,a.target_id,a.del_flag,a.top_flag,b.create_timeFROM im_chat aINNER JOIN (SELECT chat_id, max(create_time) create_time FROM im_message GROUP BY chat_id) bON a.id = b.chat_idWHERE a.del_flag = FALSEAND a.user_id = #{userId}ORDER BY a.top_flag, b.create_time</select></mapper>
package com.qiangesoft.im.mapper;import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.qiangesoft.im.entity.ImChat;
import org.apache.ibatis.annotations.Param;import java.util.List;/*** <p>* 聊天 Mapper 接口* </p>** @author qiangesoft* @date 2024-02-07*/
public interface ImChatMapper extends BaseMapper<ImChat> {/*** 聊天列表** @return*/List<ImChat> listChat(@Param("userId") Long userId);}

service

package com.qiangesoft.im.service;import com.baomidou.mybatisplus.extension.service.IService;
import com.qiangesoft.im.entity.ImChat;
import com.qiangesoft.im.pojo.vo.ImChatVO;import java.util.List;/*** <p>* 聊天 服务类* </p>** @author qiangesoft* @date 2024-02-07*/
public interface IImChatService extends IService<ImChat> {/*** 删除聊天** @param id*/void removeChat(Long id);/*** 聊天列表** @return*/List<ImChatVO> listChat();/*** 置顶聊天** @param id*/void setTop(Long id);/*** 取消置顶聊天** @param id*/void cancelTop(Long id);
}
package com.qiangesoft.im.service.impl;import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qiangesoft.im.auth.UserUtil;
import com.qiangesoft.im.core.constant.ChatTypeEnum;
import com.qiangesoft.im.entity.*;
import com.qiangesoft.im.mapper.ImChatMapper;
import com.qiangesoft.im.pojo.bo.ImChatMessageBO;
import com.qiangesoft.im.pojo.vo.ImChatVO;
import com.qiangesoft.im.pojo.vo.ImMessageVO;
import com.qiangesoft.im.pojo.vo.SysUserVo;
import com.qiangesoft.im.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;import java.util.*;
import java.util.stream.Collectors;/*** <p>* 聊天 服务实现类* </p>** @author qiangesoft* @date 2024-02-07*/
@Service
public class ImChatServiceImpl extends ServiceImpl<ImChatMapper, ImChat> implements IImChatService {@Autowiredprivate ISysUserService sysUserService;@Autowiredprivate IImFriendService friendService;@Autowiredprivate IImGroupService groupService;@Autowiredprivate IImGroupUserService groupUserService;@Autowiredprivate IImMessageService messageService;@Overridepublic void removeChat(Long id) {LambdaUpdateWrapper<ImChat> updateWrapper = new LambdaUpdateWrapper<>();updateWrapper.eq(ImChat::getId, id).set(ImChat::getDelFlag, true);baseMapper.update(null, updateWrapper);}@Overridepublic List<ImChatVO> listChat() {List<ImChatVO> groupVOList = new ArrayList<>();Long userId = UserUtil.getUserId();List<ImChat> chatList = baseMapper.listChat(userId);if (CollectionUtils.isEmpty(chatList)) {return groupVOList;}// 聊天列表对象信息List<Long> friendIdList = chatList.stream().filter(e -> ChatTypeEnum.PERSON.getCode().equals(e.getChatType())).map(ImChat::getTargetId).collect(Collectors.toList());Map<Long, ImFriend> friendMap = new HashMap<>();Map<Long, SysUser> sysUserMap = new HashMap<>();if (!CollectionUtils.isEmpty(friendIdList)) {List<ImFriend> friendList = friendService.listByIds(friendIdList);friendMap = friendList.stream().collect(Collectors.toMap(ImFriend::getId, imFriend -> imFriend));List<Long> friendUserIdList = friendList.stream().map(ImFriend::getFriendUserId).collect(Collectors.toList());sysUserMap = sysUserService.listByIds(friendUserIdList).stream().collect(Collectors.toMap(SysUser::getId, sysUser -> sysUser));}List<Long> groupIdList = chatList.stream().filter(e -> ChatTypeEnum.GROUP.getCode().equals(e.getChatType())).map(ImChat::getTargetId).collect(Collectors.toList());Map<Long, ImGroup> groupMap = new HashMap<>();if (!CollectionUtils.isEmpty(groupIdList)) {groupMap = groupService.listByIds(groupIdList).stream().collect(Collectors.toMap(ImGroup::getId, imGroup -> imGroup));}// 未读消息List<Long> chatIdList = chatList.stream().map(ImChat::getId).collect(Collectors.toList());List<ImChatMessageBO> unReadMessageList = messageService.listChatUnreadMessage(userId, chatIdList);// 最新消息List<ImMessage> latestMessageList = messageService.listLatestMessage(userId, chatIdList);List<Long> friendChatIdList = chatList.stream().filter(e -> ChatTypeEnum.PERSON.getCode().equals(e.getChatType())).map(ImChat::getId).collect(Collectors.toList());List<Long> groupChatIdList = chatList.stream().filter(e -> ChatTypeEnum.GROUP.getCode().equals(e.getChatType())).map(ImChat::getId).collect(Collectors.toList());List<ImMessage> friendLatestMessageList = latestMessageList.stream().filter(e -> friendChatIdList.contains(e.getChatId())).collect(Collectors.toList());List<ImMessage> groupLatestMessageList = latestMessageList.stream().filter(e -> groupChatIdList.contains(e.getChatId())).collect(Collectors.toList());// 昵称List<Long> sendFriendIdList = friendLatestMessageList.stream().map(ImMessage::getSenderId).collect(Collectors.toList());Map<Long, String> remarkMap = new HashMap<>();if (!CollectionUtils.isEmpty(sendFriendIdList)) {LambdaQueryWrapper<ImFriend> fqueryWrapper = new LambdaQueryWrapper<>();fqueryWrapper.eq(ImFriend::getUserId, userId).in(ImFriend::getFriendUserId, sendFriendIdList);remarkMap = friendService.list(fqueryWrapper).stream().collect(Collectors.toMap(ImFriend::getFriendUserId, ImFriend::getRemark));}List<Long> sendGroupIdList = groupLatestMessageList.stream().map(ImMessage::getSenderId).collect(Collectors.toList());Map<Long, String> nicknameMap = new HashMap<>();if (!CollectionUtils.isEmpty(groupIdList) && !CollectionUtils.isEmpty(sendGroupIdList)) {LambdaQueryWrapper<ImGroupUser> gqueryWrapper = new LambdaQueryWrapper<>();gqueryWrapper.in(ImGroupUser::getGroupId, groupIdList).in(ImGroupUser::getUserId, sendGroupIdList);nicknameMap = groupUserService.list(gqueryWrapper).stream().collect(Collectors.toMap(ImGroupUser::getUserId, ImGroupUser::getNickName));}for (ImChat chat : chatList) {ImChatVO vo = new ImChatVO();vo.setId(chat.getId());
//            vo.setAvatar(avatarMap.get());Long targetId = chat.getTargetId();String chatType = chat.getChatType();vo.setTargetId(targetId);vo.setChatType(chatType);// 未读消息数Optional<ImChatMessageBO> first = unReadMessageList.stream().filter(e -> e.getChatId().equals(chat.getId())).findFirst();Integer unreadNum = first.isPresent() ? first.get().getUnreadNum() : 0;vo.setUnreadNum(unreadNum);String name;String avatar;if (ChatTypeEnum.PERSON.getCode().equals(chatType)) {ImFriend friend = friendMap.get(targetId);name = friend.getRemark();SysUser sysUser = sysUserMap.get(friend.getFriendUserId());avatar = sysUser.getAvatar();Optional<ImMessage> firstLatest = friendLatestMessageList.stream().filter(e -> e.getChatId().equals(chat.getId())).findFirst();if (firstLatest.isPresent()) {ImMessage message = firstLatest.get();ImMessageVO messageVO = new ImMessageVO();messageVO.setId(message.getId());messageVO.setMessageType(message.getMessageType());messageVO.setMessage(message.getMessage());messageVO.setReadFlag(false);messageVO.setSendTime(message.getCreateTime());// 发送人SysUserVo sysUserVo = new SysUserVo();Long senderId = message.getSenderId();sysUserVo.setId(senderId);sysUserVo.setNickName(remarkMap.get(senderId));messageVO.setSender(sysUserVo);vo.setLatestMessage(messageVO);}} else {ImGroup group = groupMap.get(targetId);name = group.getName();avatar = group.getAvatar();Optional<ImMessage> firstLatest = groupLatestMessageList.stream().filter(e -> e.getChatId().equals(chat.getId())).findFirst();if (firstLatest.isPresent()) {ImMessage message = firstLatest.get();ImMessageVO messageVO = new ImMessageVO();messageVO.setId(message.getId());messageVO.setMessageType(message.getMessageType());messageVO.setMessage(message.getMessage());messageVO.setReadFlag(false);messageVO.setSendTime(message.getCreateTime());// 发送人SysUserVo sysUserVo = new SysUserVo();Long senderId = message.getSenderId();sysUserVo.setId(senderId);sysUserVo.setNickName(nicknameMap.get(senderId));messageVO.setSender(sysUserVo);vo.setLatestMessage(messageVO);}}vo.setName(name);vo.setAvatar(avatar);groupVOList.add(vo);}return groupVOList;}@Overridepublic void setTop(Long id) {LambdaUpdateWrapper<ImChat> updateWrapper = new LambdaUpdateWrapper<>();updateWrapper.eq(ImChat::getId, id).set(ImChat::getTopFlag, true);baseMapper.update(null, updateWrapper);}@Overridepublic void cancelTop(Long id) {LambdaUpdateWrapper<ImChat> updateWrapper = new LambdaUpdateWrapper<>();updateWrapper.eq(ImChat::getId, id).set(ImChat::getTopFlag, false);baseMapper.update(null, updateWrapper);}}
package com.qiangesoft.im.controller;import com.qiangesoft.im.pojo.vo.ImChatVO;
import com.qiangesoft.im.pojo.vo.ResultInfo;
import com.qiangesoft.im.service.IImChatService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;import java.util.List;/*** <p>* 群组 前端控制器* </p>** @author qiangesoft* @date 2024-02-07*/
@Api(tags = "聊天")
@RequiredArgsConstructor
@RestController
@RequestMapping("/im/chat")
public class ImChatController {private final IImChatService chatService;@DeleteMapping("/{id}")@ApiOperation(value = "删除聊天")public ResultInfo<Void> removeChat(@PathVariable Long id) {chatService.removeChat(id);return ResultInfo.ok();}@GetMapping@ApiOperation(value = "聊天列表")public ResultInfo<List<ImChatVO>> listChat() {return ResultInfo.ok(chatService.listChat());}@PutMapping("/setTop/{id}")@ApiOperation(value = "置顶聊天")public ResultInfo<Void> setTop(@PathVariable Long id) {chatService.setTop(id);return ResultInfo.ok();}@PutMapping("/cancelTop/{id}")@ApiOperation(value = "取消置顶聊天")public ResultInfo<Void> cancelTop(@PathVariable Long id) {chatService.cancelTop(id);return ResultInfo.ok();}}

三、消息发送接收测试

在这里插入图片描述
在这里插入图片描述

四、源码地址

源码地址:https://gitee.com/qiangesoft/boot-business/tree/master/boot-business-im

后续内容见下章

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.rhkb.cn/news/263723.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

第3部分 原理篇2去中心化数字身份标识符(DID)(3)

3.2.2.4. DID文档 (DID Document) 本聪老师&#xff1a;DID标识符和DID URL还都只是ID&#xff0c;必须为它附加一个基本属性才可以证明是该主体独有的。这个就是我们下面介绍的DID文档。 本聪老师&#xff1a;每个DID标识符都唯一对应一个DID文档&#xff0c;也可以说&#x…

kubernetes负载均衡部署

目录 1.新master节点的搭建 对master02进行初始化配置&#xff08;192.168.88.31&#xff09; 将master01的配置移植到master02 修改master02配置文件 2.负载均衡的部署 两台负载均衡器配置nginx 部署keepalived服务 所有node节点操作 总结 实验准备&#xff1a; k8s…

LangChain Agent v0.2.0简明教程 (上)

快速入门指南 – LangChain中文网 langchain源码剖析系列课程 九天玩转Langchain! 1. LangChain是什么2. LangChain Expression Language (LCEL)Runnable 接口3. Model I/O3.1 Prompt Templates3.2 Language Model3.3 Output ParsersUse case(Q&A with RAG)1. LangChain…

C++多线程同步(上)

多线程同步 引言总述详情互斥锁示例运行结果分析条件变量示例一实现分析优化运行结果示例二实现代码运行结果示例三实现代码运行结果读写锁示例实现代码注意分析运行结果附言实现运行结果运行结果个人心得引言 项目中使用多线程,会遇到两种问题,一种是对共享资源的访问时需要…

《高效使用Redis》- 由面试题“Redis是否为单线程”引发的思考

由面试题“Redis是否为单线程”引发的思考 很多人都遇到过这么一道面试题&#xff1a;Redis是单线程还是多线程&#xff1f;这个问题既简单又复杂。说他简单是因为大多数人都知道Redis是单线程&#xff0c;说复杂是因为这个答案其实并不准确。 难道Redis不是单线程&#xff1f…

redis哨兵机制

目录 前言 1.基本概念 2.安装部署(基于docker) 3.重新选举 4.选举原理 5.总结 前言 Redis的主从复制模式下&#xff0c;一旦主节点由于故障不能提供服务&#xff0c;需要人工进行主从切换&#xff0c;同时大量的客户端需要被通知切换到新的主节点上&#xff0c;对于上了一…

MATLAB:数组与矩阵

2.1 数组运算 数组运算时MATLAB计算的基础。由于MATLAB面向对象的特性&#xff0c;这种数值数组称为MATLAN最重要的一种内建数据类型&#xff0c;而数组运算就是定义这种数据结果的方法。 2.1.1 数组的创建和操作 在MATLAB中一般使用方括号“[]”、逗号“,”、空格和分号“;…

详解 CSS 选择器

详解 CSS 选择器 选择器的功能 选中页面中指定的标签元素。 要先选中元素&#xff0c;才能设置元素的属性&#xff0c;就好比策略类指挥游戏&#xff0c;比如海岛奇兵这类的, 需要先选中单位, 再指挥该单位行动。 CSS 选择器的种类 注&#xff1a;以下介绍的选择器只是CSS2标…

Redis分布式锁的正确使用姿势

前言 分布式锁在日常开发中&#xff0c;用处非常的多。包括但不限于抢红包&#xff0c;秒杀&#xff0c;支付下单&#xff0c;幂等&#xff0c;等等场景。 分布式锁的实现方式有多种&#xff0c;包括redis实现&#xff0c;mysql实现&#xff0c;zookeeper实现等等。而其中redis…

【生活】浅浅记录

各位小伙伴们好鸭&#xff0c;今天不是技术文章&#xff0c;浅浅记录一下最近几个月的收获&#x1f60a; 新的一年&#xff0c;一起努力&#xff0c;加油加油&#xff01;

解决IDEA搜不到插件

File -> Settings -> Plugins https://plugins.jetbrains.com/ 完成以上操作即可搜到插件

R cox回归 ggDCA报错

临床预测模型的决策曲线分析&#xff08;DCA&#xff09;&#xff1a;基于ggDCA包 决策曲线分析法&#xff08;decision curve analysis&#xff0c;DCA&#xff09;是一种评估临床预测模型、诊断试验和分子标记物的简单方法。 我们在传统的诊断试验指标如&#xff1a;敏感性&a…

OpenGL ES (OpenGL) Compute Shader 计算着色器是怎么用的?

OpenGL ES (OpenGL) Compute Shader 是怎么用的? Compute Shader 是 OpenGL ES(以及 OpenGL )中的一种 Shader 程序类型,用于在GPU上执行通用计算任务。与传统的顶点着色器和片段着色器不同,Compute Shader 被设计用于在 GPU 上执行各种通用计算任务,而不是仅仅处理图形…

压缩感知常用的测量矩阵

测量矩阵的基本概念 在压缩感知&#xff08;Compressed Sensing&#xff0c;CS&#xff09;理论中&#xff0c;测量矩阵&#xff08;也称为采样矩阵&#xff09;是实现信号压缩采样的关键工具。它是一个通常为非方阵的矩阵&#xff0c;用于将信号从高维空间映射到低维空间&…

二蛋赠书十六期:《高效使用Redis:一书学透数据存储与高可用集群》

很多人都遇到过这么一道面试题&#xff1a;Redis是单线程还是多线程&#xff1f;这个问题既简单又复杂。说他简单是因为大多数人都知道Redis是单线程&#xff0c;说复杂是因为这个答案其实并不准确。 难道Redis不是单线程&#xff1f;我们启动一个Redis实例&#xff0c;验证一…

深度学习系列59:文字识别

1. 简单文本&#xff1a; 使用google加的tesseract&#xff0c;效果不错。 首先安装tesseract&#xff0c;在mac直接brew install即可。 python调用代码&#xff1a; import pytesseract from PIL import Image img Image.open(1.png) pytesseract.image_to_string(img, lan…

【算法与数据结构】1971、LeetCode寻找图中是否存在路径

文章目录 一、题目二、解法三、完整代码 所有的LeetCode题解索引&#xff0c;可以看这篇文章——【算法和数据结构】LeetCode题解。 一、题目 二、解法 思路分析&#xff1a;本题应用并查集的理论直接就可以解决&#xff1a;【算法与数据结构】回溯算法、贪心算法、动态规划、图…

相机图像质量研究(35)常见问题总结:图像处理对成像的影响--运动噪声

系列文章目录 相机图像质量研究(1)Camera成像流程介绍 相机图像质量研究(2)ISP专用平台调优介绍 相机图像质量研究(3)图像质量测试介绍 相机图像质量研究(4)常见问题总结&#xff1a;光学结构对成像的影响--焦距 相机图像质量研究(5)常见问题总结&#xff1a;光学结构对成…

Oracle迁移到mysql-表结构的坑

1.mysql中id自增字段必须是整数类型 id BIGINT AUTO_INCREMENT not null, 2.VARCHAR2改为VARCHAR 3.NUMBER(16)改为decimal(16,0) 4.date改为datetime 5.mysql范围分区必须int格式&#xff0c;不能list类型 ERROR 1697 (HY000): VALUES value for partition …

为什么在MOS管开关电路设计中使用三极管容易烧坏?

MOS管作为一种常用的开关元件&#xff0c;具有低导通电阻、高开关速度和低功耗等优点&#xff0c;因此在许多电子设备中广泛应用。然而&#xff0c;在一些特殊情况下&#xff0c;我们需要在MOS管控制电路中加入三极管来实现一些特殊功能。然而&#xff0c;不同于MOS管&#xff…