Websockets and load balancing

Spring and Java EE have nice support for websockets. For example, in Spring, you can:

@Configuration @EnableWebSocket public class WebSocketConfig implements WebSocketConfigurer { @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(new MyHandler(), "/myHandler") .addInterceptors(new HttpSessionHandshakeInterceptor()); } } 

And with the MyHandler class, you can send and listen to messages in the HTML5 webcam.

 var webSocket = new WebSocket('ws://localhost:8080/myHandler'); webSocket.onmessage = function(event) { onMessage(event) }; 

The problem is that you are running multiple servers behind a load balancer. Server A clients will not be notified of events on server B.

This problem is solved in Spring using a message broker with the Stomp protocol ( http://assets.spring.io/wp/WebSocketBlogPost.html )

Since using a handler and native html5 websites seems easier to me than the Stomp method, my questions are:

  • Is it possible to use a message broker without the Stomp protocol?
  • Are there any other possibilities to solve the problem of load balancing?
+8
java javascript spring html5 websocket
source share
1 answer

Message brokers can be used without STOMP, for example, RabbitMQ broker , it can be used with several other protocols; HTTP, AMQP, MQTT, AMQP. You can use them as an implementation of JMS.

Since there are multiple instances of the application, the best alternative is indeed a central messaging broker to process messages that should be published to customers of all applications.

Any alternative involves doing something like this manually, the servers in the backend must communicate and inform each other about these events in some way. An alternative would be to write certain events to the database and each server to poll some table, but this is the type of design that we try to avoid.

In addition, with regard to load balancing and web sockets, you must configure a load balancer to allow forwarding of HTTP Upgrade headers, which are usually disabled by default. For example, nginx needs some configuration to allow forwarding of these headers, otherwise Websockets will not work.

In this case, SockJS will automatically use some of the backup options that fire when web sockets are not possible.

+3
source share

All Articles