WebSocket 传输
本节解释如何配置底层的WebSocket服务器传输。
对于Jakarta WebSocket服务器,请将ServletServerContainerFactoryBean
添加到您的配置中。有关示例,请参阅WebSocket部分下的配置服务器。
对于Jetty WebSocket服务器,请按如下方式自定义JettyRequestUpgradeStrategy
-
Java
-
Kotlin
@Configuration
@EnableWebSocketMessageBroker
public class JettyWebSocketConfiguration implements WebSocketMessageBrokerConfigurer {
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/portfolio").setHandshakeHandler(handshakeHandler());
}
@Bean
public DefaultHandshakeHandler handshakeHandler() {
JettyRequestUpgradeStrategy strategy = new JettyRequestUpgradeStrategy();
strategy.addWebSocketConfigurer(configurable -> {
configurable.setInputBufferSize(4 * 8192);
configurable.setIdleTimeout(Duration.ofSeconds(600));
});
return new DefaultHandshakeHandler(strategy);
}
}
@Configuration
@EnableWebSocketMessageBroker
class JettyWebSocketConfiguration : WebSocketMessageBrokerConfigurer {
override fun registerStompEndpoints(registry: StompEndpointRegistry) {
registry.addEndpoint("/portfolio").setHandshakeHandler(handshakeHandler())
}
@Bean
fun handshakeHandler(): DefaultHandshakeHandler {
val strategy = JettyRequestUpgradeStrategy()
strategy.addWebSocketConfigurer {
it.inputBufferSize = 4 * 8192
it.idleTimeout = Duration.ofSeconds(600)
}
return DefaultHandshakeHandler(strategy)
}
}
除了WebSocket服务器属性外,还有STOMP WebSocket传输属性可以按如下方式自定义
-
Java
-
Kotlin
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfiguration implements WebSocketMessageBrokerConfigurer {
@Override
public void configureWebSocketTransport(WebSocketTransportRegistration registry) {
registry.setMessageSizeLimit(4 * 8192);
registry.setTimeToFirstMessage(30000);
}
}
@Configuration
@EnableWebSocketMessageBroker
class WebSocketConfiguration : WebSocketMessageBrokerConfigurer {
override fun configureWebSocketTransport(registry: WebSocketTransportRegistration) {
registry.setMessageSizeLimit(4 * 8192)
registry.setTimeToFirstMessage(30000)
}
}