Springboot2.7集成websocket及相关问题

1、集成websocket完整代码

导入maven依赖


    org.springframework.boot
    spring-boot-starter-websocket

服务端代码

(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 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 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();
    }
}

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

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)第一种:就是当前使用的注入方法。注意命名,否则不会注入成功

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

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

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 getBean(Class clazz) {
        return getApplicationContext().getBean(clazz);
    }

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

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

@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

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.(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客户端

你可能感兴趣的:(java,websocket,spring,boot,java)