Spring Websocket的多个客户端订阅

时间:2019-02-06 16:25:33

标签: java spring-webflux spring-websocket

我的目标是允许多个客户端订阅websocket,但是Spring文档似乎在WRT中非常有限。

当前的websocket处理程序实现如下:

@Component("ReactiveWebSocketHandler")
public class ReactiveWebSocketHandler implements WebSocketHandler {

    private final Flux<String> flux;

    public ReactiveWebSocketHandler() throws IOException {
        this.flux = new MyFlux();

    @Override
    public Mono<Void> handle(WebSocketSession webSocketSession) {
        return webSocketSession
                .send(flux.map(webSocketSession::textMessage))
                .and(webSocketSession.receive()
                        .map(WebSocketMessage::getPayloadAsText).log());
    }
} 

据此,我们获得了发送到客户端的字符串流。现在,websocket配置类如下:

@Configuration
public class ReactiveWebSocketConfiguration {

    @Autowired
    @Qualifier("ReactiveWebSocketHandler")
    private WebSocketHandler webSocketHandler;

    @Bean
    public HandlerMapping webSocketHandlerMapping() {
        Map<String, WebSocketHandler> map = new HashMap<>();
        map.put("/emitter", webSocketHandler);
        SimpleUrlHandlerMapping handlerMapping = new SimpleUrlHandlerMapping();
        handlerMapping.setOrder(1);
        handlerMapping.setUrlMap(map);
        return handlerMapping;
    }

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

目前,最多只有一个客户端可以订阅该服务。我试图找出的是如何促进任意数量的客户端在同一/emitter端点上侦听消息。

尝试创建相同的websocket处理程序的额外副本并将其放入处理程序映射中,但无济于事。

0 个答案:

没有答案