websocket 注入 service对象的方法

websocket注入service对象的方法

SpringBoot + WebSocket

本人使用

@Autowired

发现注入不进去,断点发现service对象为null。
猜测是

 @ServerEndpoint(value = "/dataWebSocket", encoders = ServerEncoder.class)

这个注解造成的依赖替代。

使用如下方法 亲测可行

启动类的主方法

    public static void main(String[] args) {
        ConfigurableApplicationContext run = SpringApplication.run(PeehqsApplication.class, args);
        DataStatisticsWebSocket.setApplicationContext(run);
    }

websocket服务类的配置

@ServerEndpoint(value = "/dataWebSocket", encoders = ServerEncoder.class)
@Component
public class DataStatisticsWebSocket{

    private static final Logger LOGGER = LoggerFactory.getLogger(DataStatisticsWebSocket.class);

    /**
     * 存放所有在线的客户端
     */
    private static Map<String, Session> clients = new ConcurrentHashMap<>();

    private static ApplicationContext applicationContext;

    public static void setApplicationContext(ApplicationContext applicationContext) {
        DataStatisticsWebSocket.applicationContext = applicationContext;
    }

    @OnOpen
    public void onOpen(Session session) {
        LOGGER.info("有新的客户端连接了dataWebSocket: {}", session.getId());
        //将新用户存入在线的组
        clients.put(session.getId(), session);
    }

    /**
     * 客户端关闭
     * @param session session
     */
    @OnClose
    public void onClose(Session session) {
        LOGGER.info("有用户断开dataWebSocket了, id为:{}", session.getId());
        //将掉线的用户移除在线的组里
        clients.remove(session.getId());
    }

    /**
     * 发生错误
     * @param throwable e
     */
    @OnError
    public void onError(Throwable throwable) {
        LOGGER.error("dataWebSocket发生错误");
    }

    /**
     * 收到客户端发来消息
     * @param message  消息对象
     */
    @OnMessage
    public void onMessage(String message) {
        LOGGER.info("dataWebSocket服务端收到客户端发来的消息: {}", message);
        DataStatisticsService dataStatisticsService = applicationContext.getBean(DataStatisticsService.class);
        dataStatisticsService.statisticsRefresh();
    }


    /**
     * 群发消息
     * @param message 消息内容
     */
    public void sendAll(String message) {
        for (Map.Entry<String, Session> sessionEntry : clients.entrySet()) {
            sessionEntry.getValue().getAsyncRemote().sendText(message);
        }
    }

    /**
     * @param message 消息内容
     */
    public void sendObject(Object message) {
        for (Map.Entry<String, Session> sessionEntry : clients.entrySet()) {
            LOGGER.info("dataWebSocket发送内容:{}",message.toString());
            sessionEntry.getValue().getAsyncRemote().sendObject(message);
        }
    }

    /**
     * 发送消息
     * @param session
     * @param message
     * @throws IOException
     */
    public void sendMessage(Session session, String message) throws IOException {
        if(session != null){
            try {
                session.getAsyncRemote().sendText(message);
            }
            catch (Exception e) {
                LOGGER.error("websocket发送信息失败!{}", e.getMessage());
            }
        }
    }


}

附上 websocket 发送对象的编码类

public class ServerEncoder implements Encoder.Text<OperateResult> {
    @Override
    public String encode(OperateResult operateResult)  {
        Object obj = JSONObject.toJSON(operateResult);
        return obj.toString();
    }

    @Override
    public void init(EndpointConfig endpointConfig) {

    }

    @Override
    public void destroy() {

    }
}
  • 4
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
根据提供的引用内容,可以看出在WebSocketServer类中存在注入问题。在引用\[2\]中,通过@Autowired注解将LearnedCourseCacheService注入WebSocketServer类中的cacheService属性上,但是注入失败,cacheService为null。而在引用\[3\]中,项目启动时初始化的WebSocket对象可以成功注入service,但是当新用户进入聊天时,系统会创建一个新的WebSocket对象,这时由于Spring默认管理的是单例,所以无法给第二个WebSocket对象注入service,导致注入失败。 因此,解决注入WebSocketServer的问题可以尝试以下方法: 1. 确保WebSocketServer类被正确注解为@Component,以便Spring能够扫描到并管理该类。 2. 确保LearnedCourseCacheService类被正确注解为@Service或@Component,以便Spring能够正确创建并管理该类的实例。 3. 确保WebSocketServer类中的@Autowired注解被正确使用,注入LearnedCourseCacheService时,可以尝试使用构造函数注入或者在属性上使用@Autowired注解。 4. 如果WebSocketServer类需要被多个用户连接使用,可以考虑使用@Scope注解为每个WebSocket对象创建一个新的实例,以避免注入失败的问题。 综上所述,可以尝试以上方法来解决注入WebSocketServer的问题。 #### 引用[.reference_title] - *1* *2* [WebSocketServer无法注入Bean](https://blog.csdn.net/qq_45537574/article/details/122879256)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [SpringBoot中集成websocketWebSocketServer中注入mapper为空](https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/127072530)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值