Spring 开机发送异步任务

Spring boot send async tasks

我需要将 email/sms/events 作为后台异步任务发送到 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);
    }
}

如何在不阻塞响应的情况下发送事件(无需获取return 只是一个后台任务) ?

sendEvents-调用sms/email第三部分api或者发送事件到kafka主题。

谢谢。

听起来像是 the Spring @Async annotation 的完美用例。

@Async
public void sendEvents() {
   // this method is executed asynchronously, client code isn't blocked
}

重要@Async 仅适用于 public 方法,不能从单个 class 内部调用。如果把sendEvents()方法放在UserControllerclass里面就会同步执行(因为绕过了代理机制)。创建一个单独的 class 来提取异步操作。

为了在您的 Spring 引导应用程序中启用异步处理,您必须使用适当的注释标记您的主 class。

@EnableAsync
public class Application {
    public static void main(String[] args) {
        SpringApplication application = new SpringApplication(Application.class);
        application.run(args);
    }
}

或者,您也可以将 @EnableAsync 注释放在任何 @Configuration class 上。结果是一样的。