SpringBoot集成WebSocket

1)添加websocket的依赖

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

2)添加websocket相关的配置

java 复制代码
@Configuration
public class WebsoketConfig {

    /**
     * 这个Bean会自动注册使用@ServerEndpoint注解声明的websocket endpoint
     */
    @Bean
    public ServerEndpointExporter serverEndpointExporter(){
        return new ServerEndpointExporter();
    }

    /**
     * 为了能在这个类中获取到Spring的ApplicationContext,需要把它让Spring来管理
     * */
    @Bean
    public CustomSpringConfigurator customSpringConfigurator() {
        return new CustomSpringConfigurator();
    }
}

3)添加websocket的业务处理类

java 复制代码
/**
 * websocket服务端处理程序
 * configurator属性可以从Spring容器中去获取Endpoint对象实例
 * */
@Slf4j
@Component
@ServerEndpoint(value = "/ws/{clientId}", configurator = CustomSpringConfigurator.class)
public class WebsocketServer {
	/**
     * 保存clientId和session的对应关系
     * */
    private Map<String, Session> sessionMap = new ConcurrentHashMap<>();
    @OnOpen
    public void onOpen(Session session, @PathParam("clientId")String clientId){
        log.info("客户端:{}建立连接", clientId);
        sessionMap.put(clientId, session);
    }
    @OnMessage
    public void onMessage(String msg, @PathParam("clientId")String clientId){
        log.info("收到客户端:{}的消息:{}", msg, clientId);
    }
    @OnClose
    public void onClose(@PathParam("clientId")String clientId){
        log.info("客户端:{}断开连接", clientId);
        sessionMap.remove(clientId);
    }
	/**
     * 主动向client推送消息
     * */
    public void sendToClient(String clientId, String message) throws Exception{
        Session session = sessionMap.get(clientId);
        if(session == null){
            log.error("客户端:{}不在线", clientId);
        }else{
            session.getBasicRemote().sendText(message);
        }
    }
}

注意这里的configurator属性设置的CustomSpringConfigurator,这个configurator的作用是让tomcat从SpringIOC容器中去获取Endpoint的实例,否则的话,就会出现SpringIOC中有一个Endpoint实例,tomcat还会自己去new一个Endpoint实例。

java 复制代码
public class CustomSpringConfigurator extends ServerEndpointConfig.Configurator implements ApplicationContextAware {

    /**
     * Spring application context.
     */
    private static volatile ApplicationContext applicationContext;

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

    /**
     * Endpoint的实例从Spring的IOC容器去获取,否则tomcat会自己new一个WebsocketServer的实例出来
     * */
    @Override
    public <T> T getEndpointInstance(Class<T> clazz) throws InstantiationException {
        return applicationContext.getBean(clazz);
    }
}

完整的源码下载:https://github.com/xjs1919/enumdemo下面的[websocket-demo](https://github.com/xjs1919/enumdemo/tree/master/websocket-demo)。
参考文档

相关推荐
JAVA前线15 分钟前
矛盾不会消失只会转移:AI时代的项目管理探讨
后端·团队管理
geovindu33 分钟前
python: KNeighborsClassifier K
开发语言·后端·python·算法
迦蓝叶3 小时前
自建 MaaS 卡住的地方从来不是模型:JAiRouter 开源 AI 网关的四个答案
人工智能·spring boot·开源·架构设计·maas·ai 网关
光影少年3 小时前
ts全栈开发
javascript·后端·typescript·node.js·c5全栈
头发还在的女程序员4 小时前
家政小程序系统源码IM已读记录:多端阅读状态怎样保持单调推进
java·spring boot·源码·家政·消息同步
苍何4 小时前
用 WorkBuddy 自动总结微信群聊消息,夯!
后端
苍何4 小时前
全国产算力模型,近 300B 参数,猛猛干活
后端
bai2734 小时前
主线程里 foo 和 FOO 是同一个变量,Worker 里就成了两个:Windows 上 process.env 的大小写边界
javascript·后端
苍何4 小时前
AI 视频新斩杀线来了,这下给我用爽了(附实测及提示词)
后端
泡海椒4 小时前
Java 生成人事在岗率对比 PDF:应到/实到双系列条形的参数清单
后端