首页 > 解决方案 > Spring WebClient 和长轮询

问题描述

标签: javaspringproject-reactor

解决方案


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);

推荐阅读