Spring Flux 和 Async 注释

编程入门 行业动态 更新时间:2024-10-28 05:25:31
本文介绍了Spring Flux 和 Async 注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个 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 注释

本文发布于:2023-10-30 03:01:38,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1541570.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:注释   Spring   Flux   Async

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!