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)。
参考文档

相关推荐
╰つ゛木槿1 小时前
Spring Boot 调用DeepSeek API的详细教程
java·spring boot·后端·deepseek
movee2 小时前
一台低配云主机也能轻松愉快地玩RDMA
linux·人工智能·后端
程序视点3 小时前
SpringBoot配置入门
java·spring boot·spring
程序员清风4 小时前
什么时候会考虑用联合索引?如果只有一个条件查就没有建联合索引的必要了么?
java·后端·面试
Seven974 小时前
【设计模式】掌握建造者模式:如何优雅地解决复杂对象创建难题?
java·后端·设计模式
子洋4 小时前
AnythingLLM + SearXNG 实现私有搜索引擎代理
前端·人工智能·后端
heart000_14 小时前
基于SpringBoot的智能问诊系统设计与隐私保护策略
java·spring boot·后端
汐泽学园4 小时前
基于ASP.NET校园二手交易网站设计与实现
后端·asp.net
MZWeiei5 小时前
Scala:case class(通俗易懂版)
开发语言·后端·scala