Spring 4 STOMP Websockets Heartbeat

问题描述 投票:6回答:3

我似乎找不到如何在Spring中使用websockets向客户端发送心跳的好资源!

我有一个使用此配置运行的基本服务器:

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/room");
        config.setApplicationDestinationPrefixes("/app");
    }

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

然后我使用这样的东西向订阅房间的人发送消息:

this.simpMessagingTemplate.convertAndSend("/room/" + this.roomId, message);

这是用于与服务器通信的客户端代码:

this.connect = function (roomNameParam, connectionCallback) {
    var socket = new SockJS('http://localhost:8080/channels'),

    self.stompClient = Stomp.over(socket);
    self.stompClient.connect({}, function (frame) {
        self.stompClient.subscribe('/room/' + roomNameParam, connectionCallback);
    });
};

我真的想实现心跳,以便客户端知道谁连接并发送一些数据以保持客户端和服务器同步。

我需要手动操作吗?

java spring websocket stomp
3个回答
4
投票

Spring SockJS配置包含发送心跳的设置。默认情况下,假设连接上没有发送其他消息,则每25秒发送一次心跳。有关详细信息,请参阅the Spring reference


3
投票

只需致电:

.setTaskScheduler(heartBeatScheduler());

对于要启用它的代理配置(也适用于简单代理)。

@Configuration
public class WebSocketMessageBrokerConfig extends AbstractWebSocketMessageBrokerConfigurer {

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

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/endpoint");
    }

    @Bean
    public TaskScheduler heartBeatScheduler() {
        return new ThreadPoolTaskScheduler();
    }

}

2
投票

对于简单的代理,您可以像这样配置心跳:

<websocket:message-broker application-destination-prefix="/app">
    <websocket:stomp-endpoint path="/wshandler" allowed-origins="*">
    </websocket:stomp-endpoint>
    <websocket:simple-broker prefix="/topic, /queue" heartbeat="10000,10000" scheduler="pingScheduler"/>
</websocket:message-broker>

<bean id="pingScheduler" class="org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler">
    <property name="poolSize" value="1"/>
    <property name="threadNamePrefix" value="wss-heartbeat-thread-"/>
</bean>
© www.soinside.com 2019 - 2024. All rights reserved.