作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想使用 Spring 的响应式 WebClient 来轮询使用长轮询的 REST 端点。
端点为聊天 channel 提供消息。当我调用它并且没有消息时,它会阻塞(即不返回),直到出现消息(或 30 秒过去)。
因此,在同步世界中,我会专门使用一个线程来监控这个 channel ,通过 RestTemplate 调用端点,等待结果,将其写入共享队列并开始下一个请求。然后,消费者可以对出现在队列中的新项目使用react。
在响应式(Reactive)世界中,这有点不同。理想情况下,消费者会订阅 Flux 消息。问题是如何构建这个 Flux。
逻辑应该是:
Mono<String> message = WebClient.get(). […] .bodyToMono(String.class);
// When the mono completes, create a new one just as described above
// Combine all of the monos into a Flux
flux.subscribe(message -> System.out.println("New message" + message);
switch…
运营商,但我可以找到正确的。
最佳答案
正如@123 指出的:
You can just use repeat, i.e
WebClient.get(). […] .bodyToMono(String.class).repeat()
, will give you a flux of the replies, and will only start the next one when the previous is done.
defer()
和
repeat()
:
defer()
接受 Monos 和
repeat()
的供应商完成之前的订阅后,将重新订阅 Mono。这将导致供应商再次被调用,因此将启动一个新的 http 请求。
takeUntilOther()
可以使用,它需要另一个 Publisher(如
EmitterProcessor
)。然后,在
@PreDestroy
方法,可以调用
shutdown.onNext(true)
,这将导致http请求被取消。
Mono.defer(() -> receiveMessage())
.repeat()
.takeUntilOther(shutdown)
.subscribe(message -> System.out.println("New message" + message);
关于java - Spring WebClient 和长轮询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62445591/
我是一名优秀的程序员,十分优秀!