In the previous tutorial, I showed you how to relay Websocket connection in Spring Websocket using RabbitMQ. You can also use ActiveMQ to do this. How is it in detail? We will find out together in this tutorial!
First, you need to start an ActiveMQ server, with Docker Compose, you need to expose port 61613 of the STOMP connection:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
version: '3.9' services: activemq: image: activemq:0.0.1 container_name: 'activemq' ports: - 61616:61616 - 61613:61613 - 8161:8161 volumes: - ~/Documents/data/activemq/data:/data/activemq - ~/Documents/data/activemq/log:/var/log/activemq |
then in the StompBrokerRelay configuration in the previous tutorial example, we will use ActiveMQ’s information, like this:
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 |
package com.huongdanjava.springboot.websocket; import org.springframework.context.annotation.Configuration; 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 @EnableWebSocketMessageBroker public class WebSocketConfiguration implements WebSocketMessageBrokerConfigurer { @Override public void registerStompEndpoints(StompEndpointRegistry registry) { registry.addEndpoint("/hello").withSockJS(); } @Override public void configureMessageBroker(MessageBrokerRegistry registry) { // @formatter:off registry.enableStompBrokerRelay("/topic") .setRelayHost("localhost") .setRelayPort(61613); // @formatter:on registry.setApplicationDestinationPrefixes("/app"); } } |
Run the application again, then open 2 browser windows and enter your name in this browser, you will also see that both browsers receive messages from the WebSocket server.