首页 > 解决方案 > 用反应堆开火即忘

问题描述

我的 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>.

标签: springspring-bootreactive-programmingspring-webfluxproject-reactor

解决方案


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某种原因速度变慢,那么数据生产者不会关心并继续生产项目。这是火与火机制的自然结果。


推荐阅读