Springboot2.7集成websocket及相关问题

1、集成websocket完整代码

导入maven依赖

XML 复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>

服务端代码

java 复制代码
(1)注入bean
@Configuration
@EnableWebSocket
public class WebSocketConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}
(2)服务端开放的服务及其业务逻辑
@Slf4j
@Component
@ServerEndpoint("/testcase/page/{clientId}")
//@Lazy
public class WsMessageService {

    //与某个客户端的连接会话
    private Session session;

    //存放每个客户端对应的WebSocket对象。
    private static Map<String, WsMessageService> webSocketsBeanMap = new ConcurrentHashMap<>();

    //每次连接都是一个新的会话对象,线程安全的
    String userId;

    //注入业务类。要注意setTestcaseService()的名称不能错,set后的字符串要和要注入的变量名一致。
    private static TestcaseService testcaseService;
    @Autowired
    public void setTestcaseService(TestcaseService testcaseService) {
        WsMessageService.testcaseService= testcaseService;
    }

    //private TestcaseService testcaseService = SpringContextUtil.getBean(TestcaseService.class);

    @OnOpen
    public void onOpen(Session session, @PathParam(value = "clientId") String userId) {
        this.session = session;
        this.userId = userId;
        webSocketsBeanMap.put(userId, this);
        log.info("OnOpen连接成功,userId:{},当前在线人数:{}", userId, this.getOnLineCount());
    }

    @OnMessage
    public void onMessage(String message) throws IOException {
        Session session = webSocketsBeanMap.get(this.userId).session;
        if (session==null || !session.isOpen()) {
            return;
        }
        log.info("收到客户端的消息:" + message);
        //start业务
        Integer pageNum = null;
        Integer pageSize = null;
        String pid = null;
        String vid = null;
        if (session.getRequestParameterMap().get("pageNum")!= null) {
            pageNum = Integer.valueOf(session.getRequestParameterMap().get("pageNum").get(0));
        }
        if (session.getRequestParameterMap().get("pageNum")!= null) {
            pageSize = Integer.valueOf(session.getRequestParameterMap().get("pageSize").get(0));
        }
        if (session.getRequestParameterMap().get("pid")!= null) {
            pid = session.getRequestParameterMap().get("pid").get(0);
        }
        if (session.getRequestParameterMap().get("vid")!= null) {
            vid = session.getRequestParameterMap().get("vid").get(0);
        }
        PageInfo<TestcasePageVO> pageInfo = testcaseService.findTestcaseByMultiCondition(pageNum, pageSize, pid, vid);
        //end业务
        try {
            JSONObject object = new JSONObject();
            object.put("data", pageInfo);
            object.put("code", 200);
            object.put("message", "SUCCESS");
            this.session.getBasicRemote().sendText(String.valueOf(object.toString()));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @OnClose
    public void onClose() throws IOException {
        log.info("会话关闭,关闭会话的用户Id为:{}", this.userId);
        webSocketsBeanMap.remove(this.userId);
        log.info("当前在线人数:{}", this.getOnLineCount());
    }

    @OnError
    public void onError(Session session, Throwable error) {
        log.error("连接错误:" + error.getMessage());
        error.printStackTrace();
    }

    private int getOnLineCount() {
        return webSocketsBeanMap.size();
    }
}

测试服务端的可用性。在浏览器的控制台输入以下代码可以测试。

javascript 复制代码
function initWebSocket(wsUri) {
            var websocket = new WebSocket(wsUri);
            websocket.onopen = function(evt) {
                console.log('连接建立中... '+wsUri);
            };
            websocket.onclose = function(evt) {
                console.log('连接关闭中...', evt);
            };
            websocket.onmessage = function(evt) {
                console.log('收到来自服务端的消息:', evt.data);
            };
            websocket.onerror = function(evt) {
                console.log('发生错误...', evt);
            };
            return websocket;
        }
    var websocket = initWebSocket("ws://ip:port/testcase/page/123?pid=5922cc3d03f74012a7112c931c8497d7&vid=fc2d7a6049ff4c7bafc40bf659b4e903");
        var msg, i = 0;
        var loop = setInterval(function(){
            msg = "Hello " +(i++);
            if(websocket.readyState == WebSocket.OPEN) {
                websocket.send(msg);
                console.log('已发送消息:' +msg);
            } else{
                clearInterval(loop);
                console.log('连接已关闭');
            }
        }, 10000);

2、集成websocket另一种方法(用控制台测试时返回的数据会乱码)

代码找不到了。但那种方法有一个特征就是使用的注解比当前的方法少。

3、解决业务类注入不进去的问题(两种方法,推荐第一种)

(1)第一种:就是当前使用的注入方法。注意命名,否则不会注入成功

java 复制代码
//注入业务类。要注意setTestcaseService()的名称不能错,set后的字符串要和要注入的变量名一致。
    private static TestcaseService testcaseService;
    @Autowired
    public void setTestcaseService(TestcaseService testcaseService) {
        WsMessageService.testcaseService= testcaseService;
    }

(2)第二种:自己写一个SpringContextUtil工具类,协助注入

java 复制代码
package cn.xxxxx.tmMaster.utils;

import lombok.extern.slf4j.Slf4j;
import org.mybatis.logging.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.logging.Logger;

@Slf4j
@Component
public class SpringContextUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextUtil.applicationContext = applicationContext;
    }

    /**
     * 获取 applicationContext
     */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    /**
     * 通过 name 获取 bean 对象
     */
    public static Object getBean(String name) {

        return getApplicationContext().getBean(name);
    }

    /**
     * 通过 class 获取 bean 对象
     */
    public static <T> T getBean(Class<T> clazz) {
        return getApplicationContext().getBean(clazz);
    }

    /**
     * 通过 name,clazz  获取指定的 bean 对象
     */
    public static <T> T getBean(String name, Class<T> clazz) {
        return getApplicationContext().getBean(name, clazz);
    }
}

在WsMessageService中使用如下代码注入进去,但在类上必须要@Lazy进行懒加载,否则会报错

java 复制代码
@Lazy
public class WsMessageService {
......
    private TestcaseService testcaseService = SpringContextUtil.getBean(TestcaseService.class);
......
}

不加@Lazy报错如下:org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'wsMessageService' defined in file [D:\javaworkspace\test-xxxx\tm-master\target\classes\cn\xxxxx\tmMaster\service\testcase\WsMessageService.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [cn.xxxxx.tmMaster.service.testcase.WsMessageService]: Constructor threw exception; nested exception is java.lang.NullPointerException

java 复制代码
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'wsMessageService' defined in file [D:\javaworkspace\test-xxxx\tm-master\target\classes\cn\xxxxx\tmMaster\service\testcase\WsMessageService.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [cn.xxxxx.tmMaster.service.testcase.WsMessageService]: Constructor threw exception; nested exception is java.lang.NullPointerException
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1334) ~[spring-beans-5.3.29.jar:5.3.29]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1232) ~[spring-beans-5.3.29.jar:5.3.29]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:582) ~[spring-beans-5.3.29.jar:5.3.29]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542) ~[spring-beans-5.3.29.jar:5.3.29]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.29.jar:5.3.29]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.29.jar:5.3.29]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.29.jar:5.3.29]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.29.jar:5.3.29]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:955) ~[spring-beans-5.3.29.jar:5.3.29]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:921) ~[spring-context-5.3.29.jar:5.3.29]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583) ~[spring-context-5.3.29.jar:5.3.29]
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:147) ~[spring-boot-2.7.14.jar:2.7.14]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:731) [spring-boot-2.7.14.jar:2.7.14]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:408) [spring-boot-2.7.14.jar:2.7.14]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:307) [spring-boot-2.7.14.jar:2.7.14]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1303) [spring-boot-2.7.14.jar:2.7.14]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1292) [spring-boot-2.7.14.jar:2.7.14]
    at cn.xxxxx.tmMaster.MasterApplication.main(MasterApplication.java:17) [classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_382]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_382]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_382]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_382]
    at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:50) [spring-boot-devtools-2.7.14.jar:2.7.14]
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [cn.xxxxx.tmMaster.service.testcase.WsMessageService]: Constructor threw exception; nested exception is java.lang.NullPointerException
    at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:224) ~[spring-beans-5.3.29.jar:5.3.29]
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:87) ~[spring-beans-5.3.29.jar:5.3.29]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1326) ~[spring-beans-5.3.29.jar:5.3.29]
    ... 22 common frames omitted
Caused by: java.lang.NullPointerException: null
    at cn.xxxxx.tmMaster.utils.SpringContextUtil.getBean(SpringContextUtil.java:55) ~[classes/:na]
    at cn.xxxxx.tmMaster.service.testcase.WsMessageService.<init>(WsMessageService.java:48) ~[classes/:na]
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.8.0_382]
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) ~[na:1.8.0_382]
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:1.8.0_382]
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423) ~[na:1.8.0_382]
    at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:211) ~[spring-beans-5.3.29.jar:5.3.29]
    ... 24 common frames omitted

参考资料:

SpringBoot集成WebSocket实现客户端与服务端长连接通信_springboot实现websocket客户端_拄杖忙学轻声码的博客-CSDN博客 SpringBoot集成WebSocket实现客户端与服务端长连接通信

快速搭建springboot websocket客户端_springboot实现websocket客户端_wcybaonier的博客-CSDN博客 快速搭建springboot websocket客户端

相关推荐
APP 肖提莫2 分钟前
MyBatis-Plus分页拦截器,源码的重构(重构total总数的计算逻辑)
java·前端·算法
kirito学长-Java4 分钟前
springboot/ssm太原学院商铺管理系统Java代码编写web在线购物商城
java·spring boot·后端
爱学习的白杨树4 分钟前
MyBatis的一级、二级缓存
java·开发语言·spring
Code成立15 分钟前
《Java核心技术I》Swing的网格包布局
java·开发语言·swing
中草药z21 分钟前
【Spring】深入解析 Spring 原理:Bean 的多方面剖析(源码阅读)
java·数据库·spring boot·spring·bean·源码阅读
信徒_28 分钟前
常用设计模式
java·单例模式·设计模式
神仙别闹34 分钟前
基于C#实现的(WinForm)模拟操作系统文件管理系统
java·git·ffmpeg
小爬虫程序猿35 分钟前
利用Java爬虫速卖通按关键字搜索AliExpress商品
java·开发语言·爬虫
m0_7482567839 分钟前
SpringBoot 依赖之Spring Web
前端·spring boot·spring
组合缺一40 分钟前
Solon v3.0.5 发布!(Spring 可以退休了吗?)
java·后端·spring·solon