问题描述
我需要在spring boot rest内发送电子邮件/sms/事件作为后台异步任务.
I need to send the email/sms/events as a background async task inside spring boot rest.
我的REST控制器
@RestController
public class UserController {
@PostMapping(value = "/register")
public ResponseEntity<Object> registerUser(@RequestBody UserRequest userRequest){
// I will create the user
// I need to make the asyn call to background job to send email/sms/events
sendEvents(userId, type) // this shouldn't block the response.
// need to send immediate response
Response x = new Response();
x.setCode("success");
x.setMessage("success message");
return new ResponseEntity<>(x, HttpStatus.OK);
}
}
如何在不阻止响应的情况下使sendEvents (无需获取返回只是后台任务)?
How can I make sendEvents without blocking the response (no need to get the return just a background task) ?
sendEvents-调用短信/电子邮件第三方api或将事件发送到kafka主题.
sendEvents- call the sms/email third part api or send events to kafka topic.
谢谢.
推荐答案
听起来像 Spring @Async注释.
@Async
public void sendEvents() {
// this method is executed asynchronously, client code isn't blocked
}
重要: @Async
仅适用于公共方法,不能从单个类内部调用.如果将 sendEvents()
方法放在 UserController
类中,它将被同步执行(因为绕过了代理机制).创建一个单独的类以提取异步操作.
Important: @Async
works only on the public methods and can't be called from inside of a single class. If you put the sendEvents()
method in the UserController
class it will be executed synchronously (because the proxy mechanism is bypassed). Create a separate class to extract the asynchronous operation.
为了在Spring Boot应用程序中启用异步处理,您必须使用适当的注释标记主类.
In order to enable the async processing in your Spring Boot application, you have to mark your main class with appropriate annotation.
@EnableAsync
public class Application {
public static void main(String[] args) {
SpringApplication application = new SpringApplication(Application.class);
application.run(args);
}
}
或者,您也可以将 @EnableAsync
批注放置在任何 @Configuration
类上.结果将是相同的.
Alternatively, you can also place the @EnableAsync
annotation on any @Configuration
class. The result will be the same.
这篇关于Spring Boot发送异步任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!