代码之家  ›  专栏  ›  技术社区  ›  Aleksey Kozel

如何使用Spring反应WebSocket并将其转换为通量流?

  •  4
  • Aleksey Kozel  · 技术社区  · 8 年前

    有一些 WebSocketClient 上的示例 Spring documentation :

    WebSocketClient client = new ReactorNettyWebSocketClient();
    client.execute("ws://localhost:8080/echo"), session -> {...}).blockMillis(5000);
    

    我不知道如何处理输入数据流? 在那个街区里面 {...} .

    我的意思是:我如何过滤传入的数据并将其转换为流量?

    这是我想要的。

    @GetMapping("/stream", produces = MediaType.APPLICATION_STREAM_JSON_VALUE)
        public Flux<MyRecourse> getStreaming() {
    
        //  get some data from WebSocket (CoinCap service).
        //  Transform that data into MyRecourse object
        //  Return stream to a client 
    
    }
    
    1 回复  |  直到 8 年前
        1
  •  3
  •   Artem Bilan    8 年前

    看看吧 WebSocketSession 参数 WebSocketHandler.handle() λ:

    /**
     * Get the flux of incoming messages.
     */
    Flux<WebSocketMessage> receive();
    

    看见 Spring WebFlux Workshop 了解更多信息。

    更新

        Mono<Void> sessionMono =
                client.execute(new URI("ws://localhost:8080/echo"),
                        session ->
                                Mono.empty()
                                        .subscriberContext(Context.of(WebSocketSession.class, session))
                                        .then());
    
        return sessionMono
                .thenMany(
                        Mono.subscriberContext()
                                .flatMapMany(c -> c
                                        .get(WebSocketSession.class)
                                        .receive()))
                .map(WebSocketMessage::getPayloadAsText);
    

    更新2

    或另一个选项,但阻止订阅:

        EmitterProcessor<String> output = EmitterProcessor.create();
    
        client.execute(new URI("ws://localhost:8080/echo"),
                session ->
                        session.receive()
                                .map(WebSocketMessage::getPayloadAsText)
                                .subscribeWith(output)
                                .then())
                .block(Duration.ofMillis(5000));
    
        return output;
    

    更新3

    工作中的Spring Boot应用程序: https://github.com/artembilan/webflux-websocket-demo

    主要代码如下:

        EmitterProcessor<String> output = EmitterProcessor.create();
    
        Mono<Void> sessionMono =
                client.execute(new URI("ws://localhost:8080/echo"),
                        session -> session.receive()
                                .map(WebSocketMessage::getPayloadAsText)
                                .subscribeWith(output)
                                .then());
    
        return output.doOnSubscribe(s -> sessionMono.subscribe());