javaspringspring-bootspring-websocket

Custom Jetty WebSocketPolicy with Spring6 / Spring Boot 3 Web Sockets


In older versions of Spring, a custom policy could be applied by doing the following:

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractSecurityWebSocketMessageBrokerConfigurer {

  @Override
  public void registerStompEndpoints(StompEndpointRegistry registry) {
    registry.addEndpoint("/ws").setHandshakeHandler(handshakeHandler());
    registry.addEndpoint("/ws").setHandshakeHandler(handshakeHandler()).withSockJS();
  }

  @Bean
  public DefaultHandshakeHandler handshakeHandler() {
    WebSocketPolicy policy = WebSocketPolicy.newServerPolicy();
    policy.setMaxTextMessageSize(128 * 1024);

    return new DefaultHandshakeHandler(new JettyRequestUpgradeStrategy(policy));
  }
}

For reference: Custom Jetty WebSocketPolicy with Spring Web Sockets and STOMP

With newer versions of Spring (Spring 6) the constructor in JettyRequestUpgradeStrategy with the policy as argument has been removed.

So with these changes, how to create a Custom Jetty WebSocketPolicy with Spring6 / Spring Boot 3 Web Sockets?


Solution

  • I figured it out. It now works like that:

    @Bean
    public DefaultHandshakeHandler handshakeHandler() {
        var updateStrategy = new JettyRequestUpgradeStrategy();
        updateStrategy.addWebSocketConfigurer(config -> {
           config.setMaxTextMessageSize(128 * 1024);
        });
    
        return new DefaultHandshakeHandler(updateStrategy);
    }
    

    For reference: https://docs.spring.io/spring-framework/reference/web/websocket/server.html