我的 Spring boot 应用程序中有如下方法。
public Flux<Data> search(SearchRequest request) {
Flux<Data> result = searchService.search(request);//this returns Flux<Data>
Mono<List<Data>> listOfData = result.collectList();
// doThisAsync() // here I want to pass this list and run some processing on it
// the processing should happen async and the search method should return immediately.
return result;
}
//this method uses the complete List<Data> returned by above method
public void doThisAsync(List<Data> data) {
//do some processing here
}
目前,我正在使用@Async
带注释的服务类 doThisAsync
,但不知道如何传递List<Data>
,因为我不想打电话block
。
我只有Mono<List<Data>>
.
我的主要问题是如何单独处理这个 Mono 和 search
方法应返回 Flux<Data>
.
最佳答案
1,如果您的即发即忘已经是异步返回Mono
/Flux
public Flux<Data> search(SearchRequest request)
{
return searchService.search(request)
.collectList()
.doOnNext(data -> doThisAsync(data).subscribe()) // add error logging here or inside doThisAsync
.flatMapMany(Flux::fromIterable);
}
public Mono<Void> doThisAsync(List<Data> data) {
//do some async/non-blocking processing here like calling WebClient
}
2,如果您的即发即弃确实阻塞了 I/O
public Flux<Data> search(SearchRequest request)
{
return searchService.search(request)
.collectList()
.doOnNext(data -> Mono.fromRunnable(() -> doThisAsync(data))
.subscribeOn(Schedulers.elastic()) // delegate to proper thread to not block main flow
.subscribe()) // add error logging here or inside doThisAsync
.flatMapMany(Flux::fromIterable);
}
public void doThisAsync(List<Data> data) {
//do some blocking I/O on calling thread
}
请注意,在上述两种情况下,您都会失去背压支持。如果 doAsyncThis
由于某种原因变慢,那么数据生产者不会关心并继续生产项目。这是即发即弃机制的自然结果。
关于java - 使用 react 堆即发即忘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57566465/