Spring Non-blocking Rest “Send and forget”

2019-04-10 14:53发布

问题:

I'm writing a non-blocking Spring Rest controller. My client should send a request and doesn't care for the response and doesn't need to wait.

This is my server code:

@RestController
@EnableAsync
public class testController {

@RequestMapping(value = "test", method = RequestMethod.GET)
public ResponseEntity<String> test() throws InterruptedException {
    timeConsumingMethod();
    System.out.println("I'm should be first");
    return new ResponseEntity<String>("the server is processing your request", HttpStatus.OK);
}

@Async
private void timeConsumingMethod() throws InterruptedException {
    Thread.sleep(1000*5);
    System.out.println("I'm should be second!");
}

However, When I call http://localhost:8181/test using(POSTMAN, Chrome, etc...) I get the following on the server log:

I'm should be second!

I'm should be first

AND only after waiting 5 seconds my browser shows:

the server is processing your request

Is that the correct way for a "send and forget" Behavior?

回答1:

According to the doc page the @EnableAsync should be added on configuration class.

Enables Spring's asynchronous method execution capability, similar to functionality found in Spring's XML namespace.

To be used on @Configuration classes as follows, where MyAsyncBean is a user-defined type with one or more methods annotated with either Spring's @Async annotation, the EJB 3.1 @javax.ejb.Asynchronous annotation, or any custom annotation specified via the annotation() attribute.