Fire and forget with reactor

后端 未结 2 1522
面向向阳花
面向向阳花 2020-12-06 08:54

I have a method like below in my Spring boot app.

public Flux search(SearchRequest request) {
  Flux<         


        
2条回答
  •  太阳男子
    2020-12-06 09:32

    1, If your fire-and-forget is already async returning Mono/Flux

    public Flux 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 doThisAsync(List data) {
        //do some async/non-blocking processing here like calling WebClient
    }
    

    2, If your fire-and-forget does blocking I/O

    public Flux 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) {
        //do some blocking I/O on calling thread
    }
    

    Note that in both of the above cases you lose backpressure support. If the doAsyncThis slows down for some reason, then the data producer won't care and keep producing items. This is a natural consequence of the fire-and-foget mechanism.

提交回复
热议问题