简体   繁体   中英

Is Spring Boot blocking on database operations?

I am building a backend server with Spring Boot and MongoDB, basically according to this tutorial https://spring.io/guides/gs/accessing-mongodb-data-rest/ .

All my repositories are annotated with @RepositoryRestResource. The controllers for each REST repository are annotated with @RestController.

My question is, are the database operations in a REST application in Spring Boot blocking or non-blocking? That is, do the threads that handle one specific HTTP request (eg GET ) just idle when waiting for a response from the MongoDB, or do they resume to some thread pool in the meanwhile?

I have been looking up the documentation, but I could not seem to find a specification for the thread model in this case. I have also been looking at tutorials for "Making an asynchronous application in Spring Boot", but it didn't seem like they quite covered this specific issue.

The web layer can be either blocking on non-blocking , based on the stack you are using.

If you are using a blocking stack for your web layer (for example, one based on spring-boot-starter-web ), DeferredResult can be used to make sure you don't run out of request handling threads.

See the snippet below for sample usage:

@RestController
public class EntityController {

    private ExecutorService executor;

    @GetMapping
    public DeferredResult<Entity> getEntity(/**params**/) {
        DeferredResult<Entity> result = new DeferredResult<>();
        // request thread freed and returned to the request handling thread pool
        executor.execute(() -> output.setResult(entity)
        return result;
    }

}

For a complete example on DeferredResult , see this tutorial

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