三 docker安装rabbitMQ之springboot集成stomp,实现前端主动刷新
一 场景分析
对于一些需要数据同步的场景中,例如后台数据有变化,需要程序主动刷新前端界面的数据显示,这样能提供更好的用户数据交互,能第一时间了解到资源信息的变化,而不是每次主动让用户去手动刷新。
针对前端自动刷新的场景实现可以有几个方式:
1. 采用websocket,采用长连接的方式,JS的timer定时器刷新,问题是当同时在线的用户比较多时,服务器的资源占用压力会非常大。
2. 采用rabbitmq提供的stomp的方式,进行广播的方式,前端订阅当前的queue的方式实现。由于Queue的方式,可以很大程度减少服务器的压力,以及不需要客户过多的功能耦合。具体使用到的知识参见:
https://spring.io/guides/gs/messaging-stomp-websocket/
二 集成步骤
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | WebSocketMessageBrokerConfig.java package com.wycms.framework.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.messaging.simp.config.MessageBrokerRegistry; import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker; import org.springframework.web.socket.config.annotation.StompEndpointRegistry; import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer; @Configuration //https://spring.io/guides/gs/messaging-stomp-websocket/ // @EnableWebSocketMessageBroker 注解用于开启使用 STOMP 协议来传输基于代理(MessageBroker)的消息,这时候控制器(controller) // 开始支持@MessageMapping,就像是使用 @requestMapping 一样。 @EnableWebSocketMessageBroker @Primary public class WebSocketMessageBrokerConfig implements WebSocketMessageBrokerConfigurer { @Autowired WebSocketConfig webSocketConfig; @Override public void registerStompEndpoints(StompEndpointRegistry registry) { //注册一个名为 /endpointNasus 的 Stomp 节点(endpoint),并指定使用 SockJS 协议。 registry.addEndpoint( "/endpointRefresh" ).withSockJS(); //注册一个名为 /endpointChat 的 Stomp 节点(endpoint),并指定使用 SockJS 协议。 //registry.addEndpoint("/endpointChat").withSockJS(); } @Override public void configureMessageBroker(MessageBrokerRegistry registry) { // 广播式配置名为 /nasus 消息代理 , 这个消息代理必须和 controller 中的 @SendTo 配置的地址前缀一样或者全匹配 // 点对点增加一个 /queue 消息代理 registry.enableSimpleBroker( "/refresh/getResponse" ); } } |
半斤八两开始写BLOG了
分类:
运维相关
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
2017-11-01 JAVA-基础(六) Java.io
2016-11-01 什么是反向代理,如何区别反向与正向代理