聊天室信息发送

This commit is contained in:
chanbook 2022-08-05 16:05:09 +08:00
parent 2eea1f5789
commit 3c03180134
2 changed files with 11 additions and 12 deletions

View File

@ -18,7 +18,8 @@ public class WhiteListHandler {
"/v2/api-docs/**",
"/link",
"/auth/login",
"/event/**"
"/event/**",
"/chat/room/**"
};
public void handle(HttpSecurity http) throws Exception {

View File

@ -2,14 +2,13 @@ package com.zhangshu.chat.demo.websocket;
import cn.hutool.cache.Cache;
import cn.hutool.cache.CacheUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.json.JSONUtil;
import com.zhangshu.chat.demo.entity.Room;
import com.zhangshu.chat.demo.service.RoomCache;
import com.zhangshu.chat.demo.vo.RoomUserVo;
import com.zhangshu.chat.demo.vo.UserMessageVo;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.websocket.*;
@ -26,10 +25,10 @@ public class ChatRoom {
private final Cache<String, Long> sessionUserCache = CacheUtil.newFIFOCache(16);
private final Cache<String, Session> sessionCache = CacheUtil.newFIFOCache(16);
private final Cache<Long, String> userSessionCache = CacheUtil.newFIFOCache(16);
@Autowired
RoomCache roomCache;
@Autowired
ObjectMapper objectMapper;
public static RoomCache getRoomCache() {
return SpringUtil.getBean(RoomCache.class);
}
/**
* 建立连接
@ -38,7 +37,7 @@ public class ChatRoom {
*/
@OnOpen
public void onOpen(Session session, @PathParam("userId") Long userId) {
if (!roomCache.isExistUser(userId)) {
if (!getRoomCache().isExistUser(userId)) {
sendMessage("用户不在房间中,拒绝连接", session);
return;
}
@ -56,7 +55,6 @@ public class ChatRoom {
* @param session 客户端连接对象
*/
@OnMessage
@SneakyThrows
public void onMessage(String message, Session session) {
log.info("服务端接收消息成功,消息内容:{}", message);
// 处理消息并响应给客户端
@ -65,7 +63,7 @@ public class ChatRoom {
if (Objects.isNull(userId)) {
return;
}
Room room = roomCache.getRoomByUser(userId);
Room room = getRoomCache().getRoomByUser(userId);
if (Objects.isNull(room)) {
return;
}
@ -79,7 +77,7 @@ public class ChatRoom {
.username(userVo.get().getUsername())
.message(message)
.build();
String text = objectMapper.writeValueAsString(messageVo);
String text = JSONUtil.toJsonStr(messageVo);
room.getUserList().stream()
.map(RoomUserVo::getId)
.map(userSessionCache::get)