I use STOMP.js on the front end and ActiveMQ on the back end for sending push notifications to the client. The client first subscribes to a topic with the following code:
function stompConnect() {
console.log('STOMP: Attempting connection');
// recreate the stompClient to use a new WebSocket
var socket = new SockJS('/websocket');
var stompClient = Stomp.over(socket);
stompClient.connect({}, function(frame) {
stompClient.subscribe('/topic/table-updates', function(notification){
showNotification(JSON.parse(notification.body));
});
}, function (error) {
console.log('STOMP: ' + error);
setTimeout(stompConnect, 10000);
console.log('STOMP: Reconnecting in 10 seconds');
});
}
stompConnect();
Sometimes the underlying websocket connection is lost and the client needs to reconnect and subscribe to the topic again (with 10 seconds timeout). This results in that some messages from the server are lost while the client is reconnecting. Is there any way to prevent this?
I use Spring WebSocket on the back end. Here is configuration:
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
@Value("${stomp.port}")
private Integer stompPort;
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/websocket").withSockJS();
}
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry
.enableStompBrokerRelay("/topic/")
.setRelayPort(stompPort);
}
@Bean(initMethod = "start", destroyMethod = "stop")
public BrokerService brokerService() throws Exception {
final BrokerService broker = BrokerFactory.createBroker(
String.format("broker:(vm://localhost,stomp://localhost:%d)?persistent=false", stompPort));
broker.addShutdownHook(new SpringContextHook());
return broker;
}
}
Certainly do-able.
You'll need to change some things up.
It's all described here: Using Queue Browsers to Implement Durable Topic Subscriptions
But i'll give you a quick rundown.
Some important changes to your messaging structure:
Here's a basic example:
Keep in mind that the broker can get a tad clogged with messages you'll need to follow advice on the page and: