首页 > 其他分享 >springboot整合websocket

springboot整合websocket

时间:2023-10-07 23:32:10浏览次数:29  
标签:websocket springboot userId session 整合 message public String

引入依赖

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

配置类

/**
 * websocket配置类
 */
@Configuration
public class WebSocketConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {

        return new ServerEndpointExporter();
    }
}

实现类

/**
 * websocket操作类
 */
@Component
@ServerEndpoint("/websocket/{userId}")
public class WebSocketServer {
    /**
     * 日志工具
     */
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    /**
     * 与某个客户端的连接会话,需要通过它来给客户端发送数据
     */
    private Session session;
    /**
     * 用户id
     */
    private String userId;
    /**
     * 用来存放每个客户端对应的MyWebSocket对象
     */
    private static CopyOnWriteArraySet<WebSocketServer> webSockets = new CopyOnWriteArraySet<>();
    /**
     * 用来存在线连接用户信息
     */
    private static ConcurrentHashMap<String, Session> sessionPool = new ConcurrentHashMap<String, Session>();

    /**
     * 链接成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam(value = "userId") String userId) {
        try {
            this.session = session;
            this.userId = userId;
            webSockets.add(this);
            sessionPool.put(userId, session);
            logger.info("【websocket消息】有新的连接,总数为:" + webSockets.size());
        } catch (Exception e) {
        }
    }

    /**
     * 链接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        try {
            webSockets.remove(this);
            sessionPool.remove(this.userId);
            logger.info("【websocket消息】连接断开,总数为:" + webSockets.size());
        } catch (Exception e) {
        }
    }

    /**
     * 收到客户端消息后调用的方法
     */
    @OnMessage
    public void onMessage(String message) {
        logger.info("【websocket消息】收到客户端消息:" + message);
    }

    /**
     * 发送错误时的处理
     *
     * @param session
     * @param error
     */
    @OnError
    public void one rror(Session session, Throwable error) {
        logger.error("用户错误,原因:" + error.getMessage());
        error.printStackTrace();
    }

    /**
     * 此为广播消息
     */
    public void sendAllMessage(String message) {
        logger.info("【websocket消息】广播消息:" + message);
        for (WebSocketServer webSocket : webSockets) {
            try {
                if (webSocket.session.isOpen()) {
                    webSocket.session.getAsyncRemote().sendText(message);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 此为单点消息
     */
    public void sendOneMessage(String userId, String message) {
        Session session = sessionPool.get(userId);
        if (session != null && session.isOpen()) {
            try {
                logger.info("【websocket消息】 单点消息:" + message);
                session.getAsyncRemote().sendText(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 此为单点消息(多人)
     */
    public void sendMoreMessage(String[] userIds, String message) {
        for (String userId : userIds) {
            Session session = sessionPool.get(userId);
            if (session != null && session.isOpen()) {
                try {
                    logger.info("【websocket消息】 单点消息:" + message);
                    session.getAsyncRemote().sendText(message);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

    }
}

标签:websocket,springboot,userId,session,整合,message,public,String
From: https://blog.51cto.com/AmbitionGarden/7744160

相关文章

  • springboot -- 整合 sharding-jdbc 读写分离+分库分表配置(进阶)
    sharding-jdbc说明:1、分库分表不能中途更改,取模算法的id会出错2、不支持特殊sql,包括去重,子sql,聚合等3、查询会给所有表发查询sql,带上分库,分表的字段的查询只发一条,4、查询数据要注意使用,尽量带上分库或分表字段来查询,避免多表查询sql过多取模算法假设2个表,test_0,test_1,分......
  • 基于springboot的小程序的高校后勤管理系统-计算机毕业设计源码+LW文档
    1、选题背景与意义(含国内外相关研究综述及评价)近年来,随着计算机的不断发展和深入到各个行业中并起到了很重要的作用,给人们带来了很大的便利。在这样的趋势下,高校的后勤管理显得也很重要。在《高校后勤管理系统的设计与实现》中也提到,教育的普及和日益激烈的资源竞争,对学校的教学质......
  • SpringBoot的学习
    Spring的不足Spring虽然以优雅的设计和灵活强大的功能成为JavaEE企业级框架的主流解决方案,但是使用Spring的过程中也面临着一些不足XML配置太多虽然引入了组件扫描减少了配置量,Java配置让它看上去简洁不少,但Spring还是需要不少配置。所有这些配置都会对开发进度造成影响。JavaCon......
  • docker制作springboot镜像
    以下步骤在具有Docker环境的Linux机器上操作。把springboot-1.0.0.jar放到/usr/local/springboot目录下,并在该目录下创建Dockerfile文件,内容为:FROMopenjdk:8-jdk-alpineADDspringboot-1.0.0.jar/usr/local/springboot.jarENTRYPOINT["java","-jar","/usr/local/spring......
  • 优化springboot
    在SpringBoot的Web项目中,默认采用的是内置Tomcat,当然也可以配置支持内置的jetty,内置有什么好处呢?1.方便微服务部署。2.方便项目启动,不需要下载Tomcat或者Jetty针对目前的容器优化,目前来说没有太多地方,需要考虑如下几个点线程数超时时间jvm优化针对上述的优化点来说,首......
  • SpringBoot注解
    一、注解(annotations)列表@SpringBootApplication:包含了@ComponentScan、@Configuration和@EnableAutoConfiguration注解。其中@ComponentScan让springBoot扫描到Configuration类并把它加入到程序上下文。@Configuration等同于spring的XML配置文件;使用Java代码可以检查类型安......
  • Springboot+Vue整合(二)
    今天内容1:用Vue实现了进一步的查询,通过ID进行条件查询这个内容基本上是在之前的整合的基础上做的修改流程为:页面添加搜索框<el-table-columnalign="right"><templateslot="header"slot-scope="scope"><divstyle="display:fl......
  • 人事管理系统 SpringBoot2+MyBatis+MySQL5.7
    人事管理系统一、系统介绍本系统为人事管理系统,系统分为七大模块:绩效考核,招聘管理,档案管理,工资管理,考勤管理,培训管理,系统管理。可满足小企业日常办公。本系统最大特色是有强大和灵活的权限控制功能,所有菜单,按钮功能均可由管理通过配置来控制。系统默认有四个角色:管理员,财务专......
  • 就业管理系统 SpringBoot2+MyBatis+MySQL5.7
    就业管理系统一、系统介绍本系统为就业管理系统,主要围绕高校毕业生的毕业情况进行跟踪和分析,为学校领导对专业设置优化,为高校毕业生就业方向提供参考。系统分为六大模块:就业管理,招聘咨询,通告管理,学院管理,师生管理,系统管理。系统默认有三个角色:管理员,老师,学生用户管理员(admin......
  • Springboot配置文件
    <?xmlversion="1.0"encoding="UTF-8"?><projectxmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/......