当前位置: 首页 > article >正文

SpringBoot集成WebSocket

1)添加websocket的依赖

<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>

2)添加websocket相关的配置

@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的业务处理类

/**
 * 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实例。

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


http://www.kler.cn/news/163049.html

相关文章:

  • Redis 基础—Redis Desktop Manager(Redis可视化工具)安装及使用教程
  • 如何使用玻璃材质制作3D钻石模型
  • 【conda】利用Conda创建虚拟环境,Pytorch各版本安装教程(Ubuntu)
  • IO多路转接之select
  • SQL命令---修改数据库的编码
  • 【ChatGLM3】第三代大语言模型多GPU部署指南
  • node14升级node16之后无法启动处理
  • Java编程中通用的正则表达式(二)
  • idea__SpringBoot微服务05——JSR303校验(新注解)(新的依赖),配置文件优先级,多环境切换
  • Mysql 命令行导出SQL文件和导入文件
  • mybatisplus手动获取数据源执行非主数据库事务
  • sql行转列
  • java-两个列表进行比较,判断那些是需要新增的、删除的、和更新的
  • 线性回归与逻辑回归:深入解析机器学习的基石模型
  • LinuxBasicsForHackers笔记 -- 日志系统
  • AGM CPLD 应用指南
  • 《每天一个Linux命令》 -- (5)通过sshkey密钥登录服务器
  • Could not resolve all dependencies for configuration ‘:app:androidApis‘.
  • Amazon CodeWhisperer 开箱初体验
  • JAVA程序如何打jar和war问题解决
  • CentOS系统装机流程
  • 【场景测试用例】上传文件
  • 【数据开发】Hive 多表join中的条件过滤与指定分区
  • ReactNative性能优化实践
  • Azure云WAF服务的CRS规则和DRS规则区别
  • 大数据技术3:数据仓库的ETL和分层模型
  • vite配置nework访问ip
  • 电脑知识:关于电脑使用的误区
  • Linux查看openSSL版本
  • 24、文件上传漏洞——Apache文件解析漏洞