In depth understanding of spring boot asynchronous call method @ Async

This article mainly introduces the spring boot asynchronous call method @ async for your reference and learning. Let's take a look at the detailed introduction below:

1. Use background

In daily development projects, when it is slow to access other people's interfaces or do time-consuming tasks, we don't want the program to be stuck in time-consuming tasks all the time. We want the program to execute in parallel. We can use multithreading to process tasks in parallel, or use the asynchronous processing method @ async provided by spring.

2. Asynchronous processing mode

3. @ async does not return data

Use @ enableasync to enable asynchronous annotation

Add the annotation @ async on the dealnoreturnask method of asynchronous processing

Test class:

The log print result is:

From the log, we can see that the method dealnoreturntask () is completed by asynchronous execution.

Dealnoreturnask() sets sleep 3S to simulate time-consuming tasks

Testdealnoreturnask() sets sleep 10s to confirm whether asynchronous execution is completed

4. @ async returns data

The asynchronous call returns data. Future means to obtain the execution result at a certain point in the future. The return data type can be customized

The test class uses iscancelled to judge whether the asynchronous task is cancelled, and isdone to judge whether the task is finished

The log is printed as follows. We can see that the task has been waiting for the asynchronous task to complete. Use future Get() to get the returned result of the asynchronous task

4. We can implement the asyncconfigurer interface or inherit the asyncconfigurersupport class for exception handling

When creating a thread pool in the method getasyncexecutor(), you must use executor Initialize(), otherwise an uninitialized exception of the thread pool will be reported when calling.

If you use threadpooltaskexecutor () to define a bean, you do not need to initialize it

Asynchronous exception handling class:

Asynchronous exception handling class:

summary

The above is the whole content of this article. I hope the content of this article can bring some help to your study or work. If you have any questions, you can leave a message. Thank you for your support for programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>