3

We are doing a little hackathon at work and I wanted to try some new technology to get away from the usual controller.

I started using Spring Webflux with reactive WebSockets and everything is working fine so far. I configured my WebSocket handler as follows:

import my.handler.DomWebSocketHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.HandlerMapping;
import org.springframework.web.reactive.config.WebFluxConfigurer;
import org.springframework.web.reactive.handler.SimpleUrlHandlerMapping;
import org.springframework.web.reactive.socket.WebSocketHandler;
import org.springframework.web.reactive.socket.server.support.WebSocketHandlerAdapter;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class AppConfig implements WebFluxConfigurer {

    @Autowired
    private WebSocketHandler domWebSocketHandler;

    @Bean
    public HandlerMapping webSocketMapping() {
        Map<String, WebSocketHandler> map = new HashMap<>();
        map.put("/event-emitter", domWebSocketHandler);

        SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
        mapping.setOrder(1);
        mapping.setUrlMap(map);
        return mapping;
    }

    @Bean
    public WebSocketHandlerAdapter handlerAdapter() {
        return new WebSocketHandlerAdapter();
    }
}

After some more research, I learned that it is best practice to work with one connection per client.

Furthermore using more than a web-socket per browsing session for the same application seems overkill since you can use pub/sub channels. See answer here

Is there a way to restrict the connections per client and use only one endpoint for all required client "requests" or would it be better to create additional endpoints (like you would with a normal controller)?

Thank you in advance for the help.

Sebastian
  • 858
  • 7
  • 21

0 Answers0