java - Spring WebClient 和长轮询
问题描述
解决方案
As @123 pointed out:
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.
Actually, what is required here is defer()
and repeat()
: defer()
takes a supplier of Monos and repeat()
will re-subscribe to the Mono upon completion of the previous subscription. That will cause the supplier to be called again and thus a new http request will be started.
Also, since this runs forever, it will lead to an unclean application shutdown: If a shutdown occurs, there is probably an http request in flight. To cleanly end the Flux, takeUntilOther()
can be used, which takes another Publisher (like an EmitterProcessor
). Then, in a @PreDestroy
method, you can call shutdown.onNext(true)
, which will cause the http request to be cancelled.
My solution now looks like this:
Mono.defer(() -> receiveMessage())
.repeat()
.takeUntilOther(shutdown)
.subscribe(message -> System.out.println("New message" + message);
推荐阅读
- android - 用 id 编号保存新用户
- c++ - 将 utf-8 小写转换为大写
- kotlin - Optaplanner 约束流 - 如何检查多个资源
- java - 由于被调用方法的返回值,可能在 [...] 中取消引用空指针
- java - 如何使用当前用户的数据填充 recyclerview?
- c - 为什么这个引导加载程序会崩溃?
- function - 为什么1+1=0(按键和功能)
- javafx - CDI 和 JavaFX (javafx-weaver) 集成
- mysql - 为日期时间数据选择 SQL 数据类型(兼容 MySQL 和 MSSQL)
- scala - 在 Ammonite (scala) 中重新导入脚本