Spring Websocket配置:一起使用WebSocketMessageBrokerConfigurationSupport和WebSocketConfigurer - 如何?

时间:2017-04-26 15:00:53

标签: spring websocket jetty spring-websocket java-websocket

我正在使用类

配置当前的Spring Websocket
public class WebSocketConfig extends WebSocketMessageBrokerConfigurationSupport

现在我遇到了建议Spring STOMP Websockets: any way to enable permessage-deflate on server side?

利用

public class SampleJettyWebSocketsApplication implements WebSocketConfigurer 

并覆盖

@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry)

并提供

@Bean
public DefaultHandshakeHandler handshakeHandler() 

问题, WebSocketConfigurer WebSocketMessageBrokerConfigurationSupport 之间的关系是什么?换句话说,我是否可以通过第一类API WebSocketMessageBrokerConfigurationSupport从WebSocketConfigurer实现添加配置,所以所有配置都保留在一个文件中?

1 个答案:

答案 0 :(得分:1)

WebSocketMessageBrokerConfigurationSupport实施是DelegatingWebSocketMessageBrokerConfiguration,通过@EnableWebSocketMessageBroker配置。您在自定义代码中所需要的只是WebSocketMessageBrokerConfigurer实现。而那一个被注入DelegatingWebSocketMessageBrokerConfiguration

@Autowired(required = false)
public void setConfigurers(List<WebSocketMessageBrokerConfigurer> configurers) {

这是我的测试用例的示例配置:

@Configuration
@EnableWebSocketMessageBroker
static class ServerConfig extends AbstractWebSocketMessageBrokerConfigurer {

    @Bean
    public DefaultHandshakeHandler handshakeHandler() {
        return new DefaultHandshakeHandler(new TomcatRequestUpgradeStrategy());
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/ws")
                .setHandshakeHandler(handshakeHandler())
                .setAllowedOrigins("http://foo.com")
                .addInterceptors(new HandshakeInterceptor() {

                    @Override
                    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response,
                            WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
                        return request.getHeaders().getOrigin() != null;
                    }

                    @Override
                    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response,
                            WebSocketHandler wsHandler, Exception exception) {

                    }

                })
                .withSockJS();
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry configurer) {
        configurer.setApplicationDestinationPrefixes("/app")
                .enableSimpleBroker("/topic", "/queue");
    }


}