WebScoket中不能直接@resource来通过spring管理对象

不能直接在websocket类中通过@resource来创建对象

需要通过创建静态参数 ,再通过@resource注入

第一步创建websocket静态参数

@Component
@ServerEndpoint("/live-server/liveChat/websocket/{roomId}/{userId}")
public class WebSocket {

    public static LiveService liveService;
    public static ObjectMapper objectMapper;
    public static StringRedisTemplate stringRedisTemplate;
    // 使用map来收集session,key为roomId,value为同一个房间的用户集合
    private static Map<Long, Set<Session>> rooms = new ConcurrentHashMap();

    private static ConcurrentHashMap<Long, Session> sessionMap = new ConcurrentHashMap<>();

第二步 websocket配置类

@Configuration
public class WebSocketConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter(){

        return new ServerEndpointExporter();
    }

    @Resource
    public void setMessageService(LiveService liveService){
        WebSocket.liveService = liveService;
    }

    @Resource
    public void setRedis(StringRedisTemplate stringRedisTemplate){
        WebSocket.stringRedisTemplate = stringRedisTemplate;
    }
    @Resource
    public void setObjectMapper(ObjectMapper objectMapper){
        WebSocket.objectMapper = objectMapper;
    }

上一篇:分布式锁一步步的推导


下一篇:为什么我Redis中key惊现“乱码”?