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

相关推荐
115432031q几秒前
基于SpringBoot+Vue实现的旅游景点预约平台功能十三
java·前端·后端
战族狼魂4 分钟前
基于SpringBoot+PostgreSQL+ROS Java库机器人数据可视化管理系统
java·spring boot·postgresql
Java门外汉12 分钟前
在SpringBoot中,@GetMapper和@RequestMapping有什么区别?
后端
vocal13 分钟前
谷歌第七版Prompt Engineering—第二部分
人工智能·后端
Hellohistory15 分钟前
HOTP 算法与实现解析
后端·python
半个脑袋儿16 分钟前
Java日期格式化中的“YYYY”陷阱:为什么跨年周会让你的年份突然+1?
java·后端
杰瑞达Bob17 分钟前
day1 继承、权限修饰符、重写、抽象
后端
四毛打印店22 分钟前
使用kubernetes部署jetlinks社区版
后端
Moment25 分钟前
通过爬取 B 站热门视频来带你彻底了解 Playwright 🤷🏿‍♂️🤷🏿‍♂️🤷🏿‍♂️
前端·javascript·后端
shark_chili27 分钟前
来聊聊MySQL事务隔离与MVCC的关系
后端