Spring boot send async tasks

百般思念 提交于 2021-01-02 03:28:06

问题


I need to send the email/sms/events as a background async task inside spring boot rest.

My REST controller

@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);
    }
}

How can I make sendEvents without blocking the response (no need to get the return just a background task) ?

sendEvents- call the sms/email third part api or send events to kafka topic.

Thanks.


回答1:


Sounds like a perfect use case for the Spring @Async annotation.

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

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.

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);
    }
}

Alternatively, you can also place the @EnableAsync annotation on any @Configuration class. The result will be the same.



来源:https://stackoverflow.com/questions/49936835/spring-boot-send-async-tasks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!