Asynchronous call async in spring boot integration tutorial

preface

This article mainly introduces you to the asynchronous call async of spring boot integration, and shares it for your reference and learning. I won't say more below. Let's take a look at the detailed introduction together.

What is an asynchronous call?

Asynchronous call is relative to synchronous call. Synchronous call means that the program is executed step by step in a predetermined order. Each step can be executed only after the previous step is executed. Asynchronous call can be executed without waiting for the previous step.

Asynchronous processing mode

How to implement asynchronous call?

Multithreading is the first keyword many people think of. Yes, multithreading is a way to realize asynchronous calls.

In non spring projects, what we want to implement asynchronous calls is to use multithreading. We can implement the runable interface, integrate the thread class, or use jdk1 5 executors thread pool provided above.

Strngboot provides a convenient way to execute asynchronous calls.

Follow the official example

Code entry

Maven dependency:

Startup class: add @ enableasync annotation

Controller

Simply add the @ async annotation to the method that needs to execute asynchronously

The main function runs the spirngboot project. After startup, the browser accesses: http://localhost:8080/

Console:

After waiting for a while, output the following:

Asynchronous is not executed!

Is the code wrong? After repeated inspection for several times, no obvious errors were found. I remember that spring has a similar problem with @ transactional annotation. When spring scans a class with @ transactional annotation method, a proxy class is generated to open and close transactions. In the same class, method calls are executed in the class body, and spring cannot intercept this method call.

Suddenly click into place the asynchronous task in a single class, adjust the code to the bottom:

Controller

Asynchronous task class

Console:

Access the browser and enter the following results:

Asynchronous call succeeded!

How do you know when the three asynchronous tasks are completed and what are the execution results? It can be judged by adding a fate callback

Enter the following code:

Asynchronous task class

Controller

Console output:

Browser output:

The asynchronous call is successful, and the program returns the result only when all tasks are completed!

summary

The above is the whole content of this article. I hope the content of this article has a certain reference value for 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
分享
二维码
< <上一篇
下一篇>>