本文主要是介绍副本技能-使用RabbitMQ做即时消息通讯,使用STOMP协议,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1.消息通讯的基础环境
技术使用:
- 后端使用Spring Websocket通讯,
- 前端使用SocketJS,非长连接,有心跳检测
- 信息交互使用RabbitMQ的插件Stomp
给RabbitMQ安装Stomp的插件
安装前:
安装后:
安装步骤(我的RabbitMQ是使用的Docker)
- 1.进入Docker容器RabbitMQ的后台(docker exec -it 容器ID /bin/bash)
- 2.查看RabbitMQ的插件启用情况(rabbitmq-plugins list)
- 3.启用RabbitMQ插件(rabbitmq_stomp, rabbitmq_web_stomp)
- 4.关闭RabbitMQ服务
- 5.修改Docker的端口配置文件(hostconfig.json,config.v2.json)路径:/www/server/docker/containers/容器ID
- 6.重启Docker服务,放行服务端口
- 7.启动本地服务,可以链接成功
WebSocket配置
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {private final WebSocketProperties webSocketProperties;public WebSocketConfig(WebSocketProperties webSocketProperties) {this.webSocketProperties = webSocketProperties;}@Overridepublic void configureMessageBroker(MessageBrokerRegistry registry) {registry.setApplicationDestinationPrefixes("/ws").enableStompBrokerRelay("/topic")// rabbitmq 必须开启中继插件.setRelayHost(webSocketProperties.getHost()).setRelayPort(webSocketProperties.getStompPort()).setClientLogin(webSocketProperties.getUsername()).setClientPasscode(webSocketProperties.getPassword()).setSystemLogin(webSocketProperties.getUsername()).setSystemPasscode(webSocketProperties.getPassword()).setVirtualHost(webSocketProperties.getVirtualHost());}@Overridepublic void registerStompEndpoints(StompEndpointRegistry registry) {registry.addEndpoint(SERVER_ENDPOINTS).setHandshakeHandler(new UserHandshakeHandler())// 如果走网关,请检查网关的跨域,可能依旧有跨域.setAllowedOrigins("*").withSockJS();}
}
前端代码
let gateWay = "xxx";
let token = "xxx";
// 此处路径为后端的服务端点
let socket = new SockJS(gateWay + "/center-message-service/center/msg/notification?token=" + token);
let headers = {"authorization":"Bearer " + token
}
stompClient = Stomp.over(socket);
stompClient.connect(headers, function (frame) {console.log("Connected: " + frame)updateNotificationDisplay();updateOnlineUserDisplay();// stomp订阅的路径不能用/,前缀/topic是前后端约定stompClient.subscribe('/topic/xxxx', function (message) {console.info(message);console.info("<<<<");});
})
这篇关于副本技能-使用RabbitMQ做即时消息通讯,使用STOMP协议的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!