Springboot——整合websocket并根据type区别处理

文章目录

  • 前言
  • 架构思想
  • 项目结构
  • 代码实现
    • 依赖引入
    • 自定义注解
    • 定义具体的处理类
      • 定义 TypeAWebSocketHandler
      • 定义 TypeBWebSocketHandler
    • 定义路由处理类
    • 配置类,绑定point
    • 制定前端页面
    • 编写测试接口方便跳转进入前端页面
  • 测试验证
  • 结语

前言

之前写过一篇类似的博客,但之前写的逻辑过于简单,而且所有的websocket处理都在一个处理器中完成。如果需要按照消息类型等做区分操作时,会导致所有的逻辑处理都在一个处理类中,显得过于冗余。

最近一直在想一个问题,采取websocket通信处理时,能否根据某个变量,比如type,区别进入不同的处理器中。

往期博客参考:Springboot——websocket使用

架构思想

目前考虑的是用一个公共的方法接收所有的ws请求,根据传递参数type的不同,进行分发路由到不同的处理器上完成。
在这里插入图片描述

项目结构

在这里插入图片描述

代码实现

依赖引入

使用到的技术点:websocket、aop、thymeleaf 。

<!-- aop -->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-aop</artifactId>
</dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-websocket</artifactId>
</dependency><!-- 转换相关 -->
<dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId>
</dependency>

自定义注解

新建自定义注解,标注具体的实现类,并指定唯一的类型type。

package cn.xj.aspect;import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;/*** @author xj*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE) // 仅作用于类上
public @interface WebSocketTypeHandler {/*** 指定类型* @return*/String type() default "";
}

定义具体的处理类

定义 TypeAWebSocketHandler

定义TypeAWebSocketHandler,使用自定义注解标注,并指定类型为typeA

package cn.xj.wshandler;import cn.xj.aspect.WebSocketTypeHandler;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;@Component
@WebSocketTypeHandler(type= "typeA")
public class TypeAWebSocketHandler extends TextWebSocketHandler {@Overrideprotected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {// 处理Type A类型的消息逻辑System.out.println("处理Type A消息: " + message.getPayload());session.sendMessage(new TextMessage("Type A处理结果: " + message.getPayload()));}@Overridepublic void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {// 连接关闭处理逻辑System.out.println("Type A连接关闭: " + status.getReason());}
}

定义 TypeBWebSocketHandler

TypeAWebSocketHandler一样,只是输出日志不同。

package cn.xj.wshandler;import cn.xj.aspect.WebSocketTypeHandler;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;@Component
@WebSocketTypeHandler(type = "typeB")
public class TypeBWebSocketHandler extends TextWebSocketHandler {@Overrideprotected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {// 处理Type A类型的消息逻辑System.out.println("处理Type B消息: " + message.getPayload());session.sendMessage(new TextMessage("Type B处理结果: " + message.getPayload()));}@Overridepublic void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {// 连接关闭处理逻辑System.out.println("Type B连接关闭: " + status.getReason());}
}

定义路由处理类

定义路由处理类。需要实现的功能点如下:

  • 所有的ws请求都会进入当前route中,并按照指定字段进行请求的分发。
  • 在容器启动加载完成后,就能将对应的bean识别和加载到本地缓存中。
package cn.xj.wshandler;import java.io.IOException;
import java.lang.reflect.AnnotatedElement;
import java.util.HashMap;
import java.util.Map;import cn.xj.aspect.WebSocketTypeHandler;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;@Component
public class WebSocketRouter extends TextWebSocketHandler implements InitializingBean, ApplicationContextAware,DisposableBean {/*** 类型对应实例化对象缓存*/private final Map<String, TextWebSocketHandler> handlerMap = new HashMap<>();/*** 容器*/private ApplicationContext applicationContext;/*** 用于设置 applicationcontext 属性 ApplicationContextAware实现类* @param applicationContext the ApplicationContext object to be used by this object* @throws BeansException*/@Overridepublic void setApplicationContext(ApplicationContext applicationContext) throws BeansException {this.applicationContext = applicationContext;}/*** 应用启动完成  InitializingBean 实现类* @throws Exception*/@Overridepublic void afterPropertiesSet() throws Exception {// 获取所有指定注解标识的beanMap<String, Object> handlerBeans = applicationContext.getBeansWithAnnotation(WebSocketTypeHandler.class);if (!CollectionUtils.isEmpty(handlerBeans)) {for (Object handlerBean : handlerBeans.values()) {AnnotatedElement annotatedElement = handlerBean.getClass();// 获取注解标识的值WebSocketTypeHandler webSocketTypeHandler = annotatedElement.getAnnotation(WebSocketTypeHandler.class);String type = webSocketTypeHandler.type();// 按照类型 存对应的beanhandlerMap.put(type, (TextWebSocketHandler) handlerBean);}}}/*** 应用销毁 DisposableBean 实现类* @throws Exception*/@Overridepublic void destroy() throws Exception {// help GChandlerMap.clear();}private final ObjectMapper objectMapper = new ObjectMapper();/*** ws 消息处理转发* @param session* @param message* @throws Exception*/@Overrideprotected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {try {// 转换Map<String, Object> request = objectMapper.readValue(message.getPayload(), Map.class);String type = (String) request.get("type");TextWebSocketHandler handler = handlerMap.get(type);if (handler == null) {session.sendMessage(new TextMessage("不支持的type: " + type));return;} handler.handleMessage(session,message);} catch (IOException e) {session.sendMessage(new TextMessage("消息解析错误"));}}/*** 断开连接处理* @param session* @param status* @throws Exception*/@Overridepublic void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {for (TextWebSocketHandler textWebSocketHandler : handlerMap.values()) {textWebSocketHandler.afterConnectionClosed(session,status);}}
}

配置类,绑定point

package cn.xj.config;import cn.xj.wshandler.WebSocketRouter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {@Autowiredprivate WebSocketRouter webSocketRouter;/*** 绑定前端请求地址 /websocket-endpoint* @param registry*/@Overridepublic void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {registry.addHandler(webSocketRouter, "/websocket-endpoint").setAllowedOrigins("*");// 其他绑定//registry.addHandler(webSocketRouter, "/websocket-endpoint2").setAllowedOrigins("*");}
}

制定前端页面

此处使用的是thymeleaf框架,必须引入对应的依赖。其次在src/main/resources 中需要创建一个新的目录 templates 存放前端文件。

<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF - 8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>WebSocket Example </title>
</head><body>
<script>const socket = new WebSocket('ws://localhost:8080/websocket-endpoint');socket.onopen = function (event) {console.log('WebSocket连接已建立');};socket.onmessage = function (event) {console.log('收到消息:', event.data);};socket.onclose = function (event) {console.log('WebSocket连接已关闭');};function sendMessage(type, content) {const message = {type: type,content: content};socket.send(JSON.stringify(message));}
</script>
传递来的数据值cid:
<input type="text" th:value="${cid}" id="cid" readonly />
<button onclick="sendMessage('typeA', '这是一条typeA的测试消息')">发送typeA消息</button>
<button onclick="sendMessage('typeB', '这是一条typeB的测试消息')">发送typeB消息</button>
</body></html>

编写测试接口方便跳转进入前端页面

package cn.xj.controller;import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;/*** 前端页面进入*/
@Controller
@RequestMapping("/view")
public class ViewController {/*** 测试页面跳转,携带自定义的cid信息* @param cid* @param model* @return*/@GetMapping("/socket/{cid}")public String socket(@PathVariable String cid, Model model){model.addAttribute("cid", cid);return "index";}
}

测试验证

请求前端地址,按f12打开浏览器控制台。

http://localhost:8080/view/socket/1

在这里插入图片描述
在这里插入图片描述

结语

本代码仅供测试使用,afterConnectionClosed逻辑测试中存在问题,正常使用需要进行调整。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.pswp.cn/web/82512.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

vscode命令行debug

vscode命令行debug 一般命令行debug会在远程连服务器的时候用上&#xff0c;命令行debug的本质是在执行时暴露一个监听端口&#xff0c;通过进入这个端口&#xff0c;像本地调试一样进行。 这里提供两种方式&#xff1a; 直接在命令行中添加debugpy&#xff0c;适用于python…

Hot100 Day02(移动0,乘最多水的容器、三数之和、接雨水)

移动零 题目链接 题目描述&#xff1a; 思路&#xff1a;上述蓝色箭头代表当前遍历的元素&#xff0c;红色数字则是当前空位0的位置&#xff0c;每一次遇到非0元素&#xff0c;就是讲该元素的位置和空位0的位置进行交换&#xff0c;同时空位0的下标1. 代码 class Solution …

(eNSP)配置WDS手拉手业务

1.实验拓扑 2.基础配置 [SW1]dis cu # sysname SW1 # vlan batch 10 100 110 120 # dhcp enable # interface Vlanif10ip address 192.168.10.2 255.255.255.0 # interface Vlanif100ip address 192.168.100.2 255.255.255.0dhcp select interfacedhcp server excluded-ip-add…

lua的笔记记录

类似python的eval和exec 可以伪装成其他格式的文件&#xff0c;比如.dll 希望在异常发生时&#xff0c;能够让其沉默&#xff0c;即异常捕获。而在 Lua 中实现异常捕获的话&#xff0c;需要使用函数 pcall&#xff0c;假设要执行一段 Lua 代码并捕获里面出现的所有错误&#xf…

【DeepSeek】【Dify】:用 Dify 对话流+标题关键词注入,让 RAG 准确率飞跃

1 构建对话流处理数据 初始准备 文章大纲摘要 数据标注和清洗 代码执行 特别注解 2 对话流测试 准备工作 大纲生成 清洗片段 整合分段 3 构建知识库 构建 召回测试 4 实战应用测试 关键词提取 智能总结 测试 1 构建对话流处理数据 初始准备 构建对话变量 用…

RabbitMQ 开机启动配置教程

RabbitMQ 开机启动配置教程 在本教程中&#xff0c;我们将详细介绍如何配置 RabbitMQ 以实现开机自动启动。此配置适用于手动安装的 RabbitMQ 版本。 环境准备 操作系统&#xff1a;CentOS 7RabbitMQ 版本&#xff1a;3.8.4Erlang 版本&#xff1a;21.3 步骤 1. 安装 Erla…

第N1周:one-hot编码案例

&#x1f368; 本文为&#x1f517;365天深度学习训练营中的学习记录博客 &#x1f356; 原作者&#xff1a;K同学啊 一、one-hot编码概念 自然语言处理&#xff08;NLP&#xff09;中的文本数字化&#xff1a;文字对于计算机来说就仅仅只是一个个符号&#xff0c;计算…

Linux 云服务器部署 Flask 项目(含后台运行与 systemd 开机自启)

一、准备工作 在开始正式部署之前,请确认以下前提条件已经准备好: 你有一台运行 Linux 系统(CentOS 或 Ubuntu)的服务器; 服务器有公网 IP,本例中使用:111.229.204.102; 你拥有该服务器的管理员权限(可以使用 sudo); 打算使用 Flask 构建一个简单的 Web 接口; 服务…

散货拼柜业务:多货主财务结算如何高效管理?

散货拼柜业务满足了小批量发货客户的需求&#xff0c;由于无法满足海运整柜的条件&#xff0c;其模式通常涉及多个货主共同分摊同一集装箱的运输项目。这种业务模型虽然在成本上具备优势&#xff0c;但其复杂的财务结算过程往往给公司带来了挑战。 散货拼柜业务的特点在于其小…

数据结构(7)—— 二叉树(1)

目录 前言 一、 树概念及结构 1.1树的概念 1.2树的相关概念 1.3数的表示 1.二叉树表示 2.孩子兄弟表示法 3.动态数组存储 1.4树的实际应用 二、二叉树概念及结构 2.1概念 2.2特殊的二叉树 1.满二叉树 2. 完全二叉树 2.3二叉树的性质 2.4二叉树的存储结构 1.顺序存储 2.链式存储…

SpringBoot+Vue+微信小程序校园自助打印系统

概述​​ 校园自助打印系统是现代化校园建设中不可或缺的一部分&#xff0c;基于SpringBootVue微信小程序开发的​​免费Java源码​​项目&#xff0c;包含完整的用户预约、打印店管理等功能模块。 ​​主要内容​​ ​​ 系统功能模块​​ ​​登录验证模块​​&#xff1a;…

使用 useSearchParams 的一个没有触发控制台报错的错误用法

const searchParams useSearchParams(); // navigate(/?${searchParams.toString()});//带过去的参数会把函数方法也带过去 正确写法应该是用[]解构 使用了数组解构&#xff08;destructuring&#xff09;来提取 useSearchParams 返回的数组中的第一个值 const [searchPara…

Blender的一些设置

1. 将Blender长度单位改为毫米(mm), 并设置guides Grid的缩放系数&#xff0c;避免网格不见了。 2. 布尔操作的(Apply)应用按钮在哪里&#xff1f;好吧&#xff0c;在这里&#xff1a; 可以按下 CTRL A 快捷键。 3. 模型的 移动、旋转、缩放快捷键: G&#xff0c;R&#xff0…

Inno Setup 脚本中常用术语释义

1、目录常量 {app} 应用程序所在的目录。 {win} 系统的 Windows 目录&#xff0c; “C:/WINDOWS”。 {sys} 系统的 Windows 系统&#xff08;System&#xff09;目录&#xff0c;“C:/WINDOWS/SYSTEM”。 {src} 这个文件夹指向安装程序所在的位置。 {pf} 程序…

【java面试】MySQL篇

MySQL篇 一、总体结构二、优化&#xff08;一&#xff09;定位慢查询1.1 开源工具1.2Mysql自带的慢日志查询1.3 总结 &#xff08;二&#xff09;定位后优化2.1 优化2.2 总结 &#xff08;三&#xff09;索引3.1 索引3.2 索引底层数据结构——B树3.3 总结 &#xff08;四&#…

drawio 开源免费的流程图绘制

开源地址 docker-compose 一键启动 #This compose file adds draw.io to your stack version: 3.5 services:drawio:image: jgraph/drawiocontainer_name: drawiorestart: unless-stoppedports:- 8081:8080- 8443:8443environment:PUBLIC_DNS: domainORGANISATION_UNIT: unitOR…

江科大睡眠,停止,待机模式hal库实现

修改主频我们直接在cubeMx上面修改就行了&#xff0c;很方便 睡眠&#xff0c;停止&#xff0c;待机模式是通过对电源的控制来进行的&#xff0c;相关代码在PWR文件里面 SEV&#xff08;Send Event&#xff09; void HAL_PWR_EnterSLEEPMode(uint32_t Regulator, uint8_t SL…

【黄金评论】美元走强压制金价:基于NLP政策因子与ARIMA-GARCH的联动效应解析

一、基本面&#xff1a;多因子模型解析黄金承压逻辑 1. 政策冲击因子驱动美元强势 通过NLP模型对关税政策文本进行情感分析&#xff0c;构建政策不确定性指数&#xff08;PUI&#xff09;达89.3&#xff0c;触发美元避险需求溢价。DSGE模型模拟显示&#xff0c;钢铁关税上调至…

蓝桥云课ROS一键配置teb教程更新-250604

一键配置 echo "250604已经更新不动了"git clone https://gitcode.com/ZhangRelay1/donut.gitsudo apt-key add ~/donut/ros.keysudo apt updateecho "Upgrade Mission Completed."echo "Teb Mission Begins."sudo apt install ros-kinetic-sta…

OD 算法题 B卷【服务启动】

文章目录 服务启动 服务启动 有若干连续编号的服务&#xff08;编号从0开始&#xff09;&#xff0c;服务间有依赖关系&#xff0c;启动一个指定的服务&#xff0c;请判断该服务是否可以成功启动&#xff0c;并输出依赖的前置服务编号&#xff1b;依赖关系是可以传递的&#x…