0

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.

Vish K
  • 135
  • 5
  • 14

1 Answers1

3

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.

Daniel Olszewski
  • 13,995
  • 6
  • 58
  • 65
  • Thanks, I am confused with spring batch and integration vs @Async ? are they same usecase or different ? – Vish K Apr 20 '18 at 08:14
  • This topis answers your question https://stackoverflow.com/questions/36675656/spring-batch-or-spring-boot-async-method-execution In your case, @Async seems sufficient. – Daniel Olszewski Apr 20 '18 at 08:33