三 docker安装rabbitMQ之springboot集成stomp,实现前端主动刷新
一 场景分析
对于一些需要数据同步的场景中,例如后台数据有变化,需要程序主动刷新前端界面的数据显示,这样能提供更好的用户数据交互,能第一时间了解到资源信息的变化,而不是每次主动让用户去手动刷新。
针对前端自动刷新的场景实现可以有几个方式:
1. 采用websocket,采用长连接的方式,JS的timer定时器刷新,问题是当同时在线的用户比较多时,服务器的资源占用压力会非常大。
2. 采用rabbitmq提供的stomp的方式,进行广播的方式,前端订阅当前的queue的方式实现。由于Queue的方式,可以很大程度减少服务器的压力,以及不需要客户过多的功能耦合。具体使用到的知识参见:
https://spring.io/guides/gs/messaging-stomp-websocket/
二 集成步骤
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了

浙公网安备 33010602011771号