gpt4 book ai didi

spring-websocket - 如何使用 Spring Reactive WebSocket 并将其转换为 Flux 流?

转载 作者:行者123 更新时间:2023-12-01 01:48:02 26 4
gpt4 key购买 nike

有一些WebSocketClient关于 Spring documentation 的示例:

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

我不确定如何处理传入的数据流?
在那块里面 {...} .

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

这是我想要的。
@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

}

最佳答案

看看那个 WebSocketSession WebSocketHandler.handle() 的参数 lambda :

/**
* 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());

关于spring-websocket - 如何使用 Spring Reactive WebSocket 并将其转换为 Flux 流?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47065219/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com