我有一个 Spring Flux 应用程序,有时我需要在后台执行一些繁重的任务,调用者(HTTP 请求)不需要等到该任务完成.
I have a Spring Flux application where at some point I need to execute some heavy task on the background, the caller (a HTTP request) does not need to wait until that task completes.
如果没有反应器,我可能只会使用 Async 注释,在不同的线程上执行该方法.使用 reactor,我不确定我是否应该继续使用这种方法,或者是否已经有一个内置机制可以让我实现这一点.
Without reactor, I would just probably use the Async annotation, executing that method on a different thread. With reactor, I am not sure if I should proceed with that approach or if there is already a built-in mechanism that allows me to accomplish this.
例如,给定一个接受 Resource 对象的 Controller:
For example, given a Controller that accepts a Resource object:
@PostMapping("/create") public Mono<Resource> create(@Valid @RequestBody Resource r) { processor.run(r); // the caller should not wait for the resource to be processed return repository.save(r); }还有一个 Processor 类:
@Async void run(Resource r) { WebClient webClient = WebClient.create("localhost:8080"); Mono<String> result = webClient.get() .retrieve() .bodyToMono(String.class); String response = result.block(); //block for now }/create 的 HTTP 调用方不需要等到 run 方法完成.
The HTTP caller for /create should not need to wait until the run method completes.
推荐答案如果您正在寻找 fire-and-forget 模式实现,您可以订阅您的发布者
If you are looking for the fire-and-forget pattern implementation, you could just subscribe your publisher
@PostMapping("/create") public Mono<Resource> create(@Valid @RequestBody Resource r) { run(r).subscribe(); return repository.save(r); } Mono<Void> run(Resource r) { WebClient webClient = WebClient.create("localhost:8080"); return webClient.get() .retrieve() .bodyToMono(String.class) .then(); }如果您的发布者执行阻塞操作,则应该使用弹性或并行调度程序在其他线程上订阅它.
If your publisher executes blocking operations it should be subscribed on other thread with elastic or parallel scheduler.
更多推荐
Spring Flux 和 Async 注释
发布评论