websocket中spring注入失效

一个null指针引发的思考

场景

首页有个websocket的连接,初始化的时候需要去后台获取数据,然后会定时5s一次获取后端的数据。

代码

SpringBoot入口类

扫描注册到spring中

package com;

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

@ComponentScan(basePackages = {
   com.xxx})//扫描com.xxx及子包
@EnableScheduling//开启定时任务
@SpringBootApplication //启动springboot
public class Application implements ApplicationRunner {
   

  public static void main(String[] args) throws Exception {
   
    SpringApplication.run(Application.class, args);
  }

  @Override
  public void run(ApplicationArguments args) throws Exception {
   
  }

}
配置类
package com.xxx.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

@Configuration
public class WebSocketConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}
websocket类

实现和web前端的交互,获取web后端的数据

package com.xxx.webSocket;


import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.xxx.service.IOverviewService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 首页概况
 *
 * @author 阿明
 * @date 2023/11/30-15:39
 */
@Slf4j
@ServerEndpoint("/websocket/v3/overview")
@Component
public class WebSocketServerOverview {
   
    private static final int CARD = 5;
    private static final Map<String, DataWrap<OverviewVo>> dataWrapMap = new ConcurrentHashMap<>();

    @Resource
    private IOverviewService overviewService;

    @Scheduled(cron = "*/5 * * * * ? ")
    public void sendCard() throws InterruptedException {
   
        try {
   
            for (DataWrap<OverviewVo> value : dataWrapMap.values()) {
   
                    OverviewVo overviewData = overviewService.card();//new CardVo(totalDatas, cls, toDay, history, totalRules, use, cpu, hardDisk, memory, traffic);
                    value.getSession().getBasicRemote().sendText(JSONUtil.toJsonStr(overviewData));
            }
        } catch (IOException e) {
   
            log.error("websocket overview错误:", e);
        }
    }


    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session) {
   

        log.info("连接成功");
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session) {
   
        Iterator<DataWrap<OverviewVo>> iterator = dataWrapMap.values().iterator();
        while (iterator.hasNext()) {
   
            DataWrap<OverviewVo> value = iterator.next();
            if (value.getSession().equals(session)) {
   
                //清除缓存数据 value.getType()
                iterator.remove();
            }
        }
        log.info("连接关闭")
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值