一个null指针引发的思考
websocket中spring注入失效
场景
首页有个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("连接关闭")