简体   繁体   中英

Spring Non-blocking Rest "Send and forget"

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?

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.

why don't you use this: https://www.baeldung.com/spring-webclient-resttemplate

Webflux client seems to do the same. I was searching for a similar solution where 1 microservice calls multiple microservices async and this fits the model

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM