使用Spring整合WebSocket实时通信技术,在消息处理过程中,如果消息处理的逻辑很多,会造成消息处理类的代码臃肿,代码冗长;此时可以借助于Spring为我们提供的WebSocketHandlerDecorator装饰类,来分离不同的逻辑处理部分,使得代码清晰起来
参考Spring文档:https://docs.spring.io/spring-framework/docs/5.3.4/reference/html/web.html#websocket
- SpringBoot版本 2.4.5
WebSocketHandlerDecorator的用途
- 降低代码耦合度
- 动态增加类的行为
- 符合单一职责的设计原则
- 符合开闭原则的设计原则
使用方式
Spring为我们提供的WebSocketHandlerDecorator装饰者类,是装饰者模式的实现,基于该类,可以用它装饰一些具有额外行为的消息处理器
举例~
假如我们通过WebSocket收到的消息需要持久化到数据库中,elasticsearch搜索引擎中,便于后续业务流程中用到,这时就可以用WebSocketHandlerDecorator来装饰之前编写的消息处理类,不需要修改之前的消息处理类代码!
以下给出示例代码,来演示WebSocketHandlerDecorator的使用过程
1.新建PersistenceToDatabaseWebSocketHandlerDecorator,来处理消息持久化到数据库的逻辑

2.新建PersistenceToElasticsearchWebSocketHandlerDecorator,来处理消息持久化到elasticsearch的逻辑

3.配置装饰类生效,将消息处理类一层层的传入构造函数中

运行效果
启动工程,通过前端代码发送消息来测试
完整前端代码参考:https://github.com/netbuffer/UItest/blob/master/websocket/index.html

观察后端日志输出,可以看到我们的装饰类相应逻辑已经运行了

如果后续不需要将消息写入数据库或者elasticsearch中,那就可以修改消息处理类的配置部分,将装饰类删除,而不需要直接修改原有的消息处理代码部分

完整测试工程参考:https://github.com/netbuffer/spring-boot-websocket-demo
基于SpringBoot的websocket连接访问控制方案:https://www.jianshu.com/p/46407059ccd7
使用SpringBoot搭建实时通信服务:https://www.jianshu.com/p/e7069819b800
SpringBoot整合websocket获取http会话信息:https://www.jianshu.com/p/d29032fb730b
网友评论