Spring boot uses webasynctask to return results asynchronously
In spring boot (spring MVC), requests are synchronized by default. A thread is responsible for a request from the past to the end. Many times, in order to improve throughput, we need to asynchronize some operations. In addition to asynchronizing some time-consuming business logic, our query interface can also execute asynchronously.
A request to the service is received by the thread of the web container, such as http-nio-8084-exec-1
We can use webasynctask to distribute this request to a new thread for execution, and http-nio-8084-exec-1 can receive the processing of other requests. Once the returned data of webasynctask is available, it will be called again and processed to return the value to the requester in an asynchronous manner.
The example code is as follows:
You can see the output results as follows:
/Login called thread ID is: http-nio-8084-exec-1
Successful execution thread ID is: mvcasync1
The thread before executing the business logic is not the same as the thread specifically processing the business logic, which has achieved our goal.
Then I did a concurrency test and found that I kept creating the thread mvcasync1. I was thinking, didn't I use the thread pool?
After reading the source code, I found that this is true. Webasyncmanager is the central class for spring MVC to manage async processing.
The default is to use simpleasynctaskexecutor, which will create a new thread for each request
If the task specifies an executor, use the task specified. If not, use the default simpleasynctask executor
We can configure async's thread pool without specifying it separately for each task
Via configurer setTaskExecutor(threadPoolTaskExecutor()); To specify
After configuration, you can see that the output thread name starts with YJH, and new threads will not be created all the time
You can see the output results as follows:
summary
The above is what Xiaobian introduced to you. Spring boot uses webasynctask to asynchronously return results. I hope it will be helpful to you. If you have any questions, please leave me a message and Xiaobian will reply to you in time. Thank you very much for your support for the programming tips website!