The difference between webSyncTask-based asynchronous task processing and @async annotated asynchronous task processing is not clear at the time of the comment, so I went to learn! Take this opportunity to summarize as follows:
Step 1: Annotate asynchronous task development in Spring
- 1. Add to the configuration class
@@EnableAsync
Annotation, and make sure Spring can scan for the annotation - 2. Asynchronous task definition, adopted
@Async
define - 3. Finally, call the asynchronous task just like calling the ordinary method. For the value of the asynchronous task that has returned the result, you can pass
FutureResult
To obtain
For example code for annotation-based asynchronous task programming, the editor has incorporated it into the code from the previous blog post:
The code address is github.com/SmallerCode…
Haha, give xiaobian a start!
Basic principles of asynchronous tasks
Asynchronous small make up also have mentioned before, the concept of the simple truth is that I find you, I don’t have to wait for you to get things done, I can afford to do other things again, an example is when you send WeChat messages to your friends, as the message might be more accurate, after waiting for you friends see informed you will be able to get things done. Of course, in the case of a Web request response, asynchrony can be understood as releasing the thread currently processing the request, secretly opening a thread in the background to execute it, and then returning after the execution, allowing the thread processing the request to handle other incoming requests.
The reason why nginx concurrency is so good, I think Linux’s epoll model can be understood. Also, take a look at servlet 3.0’s support for asynchrony.
Asynchronous task types
Since the thread processing the request has been freed, our asynchronous task thread is required to be associated with the context of the current request in order to respond properly. Asynchronous tasks are not always smooth, and there are three possible scenarios:
- 1. It may perform normally and return no value,
void
The statement - 2. It may return a result
- 3. It may throw an exception message that needs to be handled
For getting the return value
A Future object can be returned using ResultFuture, and the return value can be obtained using the Future object’s GET method.
For exception information processing
Based on exception handling and annotations of the asynchronous task based on WebAsynctask is different, the former using custom exception class AsyncConfigurer AsyncUncaughtExceptionHandler implementation class for processing.
Thank you for reading, all the code mentioned above can be seen at the above github address, if there is any error, welcome pr, if it is helpful to you, please give a star, moya!