The Async annotation in Spring realizes the method steps of asynchronous operation

  • 2021-07-24 11:03:05
  • OfStack

Asynchronous execution is generally used to send 1 message data, and the data 1 property does not require too high a scenario. For spring, it encapsulates this asynchronism and can be realized with 1 annotation.

What is an asynchronous call?

Before explaining asynchronous invocation, let's look at the definition of synchronous invocation. Synchronization is the sequential execution of the whole process, when each process is completed and the results are returned. Asynchronous invocation only sends the invocation instruction, and the caller does not need to wait for the invoked method to be completely executed; Instead, continue with the following process. For example, in a certain call, three procedure methods, A, B and C, need to be called in sequence. If they are all called synchronously, they need to be executed sequentially before the process is counted as finished; If B is an asynchronous calling method, after A is executed, B is called, instead of waiting for B to complete, C is started, and after C is executed, it means that this process is finished.

Introduction to @ Async

In Spring, the method based on @ Async annotation is called asynchronous method. When these methods are executed, they are executed in separate threads, and the caller does not have to wait for it to complete before proceeding with other operations.

It is divided into asynchronous calls without parameters; Asynchronous invocation with parameters; Invoke an asynchronous thread that returns Future

Transaction Mechanism in @ Async Call

The method of annotation in @ Async is also applicable to annotation in @ Transactional; When it invokes a database operation, it cannot generate transaction management control because it is based on asynchronous processing operations. How do you add transaction management to these operations? You can place methods that require transaction management operations inside asynchronous methods and add @ Transactional to methods that are called internally. For example, the method A, annotated with @ Async/@ Transactional, does not produce the purpose of transaction control. Method B is annotated with @ Async, C is called in B, and D and C/D are annotated with @ Transactional respectively, so the purpose of transaction control can be realized.

Usage

1. Open @ EnableAsync annotation when the program starts

2. Create a new type, create an asynchronous method, and add @ Async annotation to the method

3. In the business code, @ Autowired injects your type and uses it

We can notice that when configuring task, there are parameters that let us configure the number of thread pools. Because of this implementation method, adding @ async annotation to method calls in the same class is invalid! The reason is that when you are in the same class, the method call is executed in the class body, and spring cannot intercept this method call.

Several modes of Async

1. If there is no return value, it will not block the main thread, which is equivalent to opening a new thread to perform this task in the background


  @Async
  public String sayHello2() throws InterruptedException {
    Thread.sleep(2 * 1000);// In the network connection   . . . Message is being sent. . . 
    return " I love you !";//  The caller will return immediately after calling , So return null
  }

1. With a return value, the return type must be Future < > It opens a new thread to execute the task, blocks the main thread, and returns the result to the main thread after execution


 @Async
 public Future<String> asyncFunc() throws InterruptedException {
  int thinking = 2;
  Thread.sleep(thinking * 1000);
  System.out.println("async!");
  return new AsyncResult<String>(" Sending the message used " + thinking + " Seconds ");
 }

Invoke method


 @GetMapping("/lind-demo/asyncFunc")
 public void async() throws Exception {
  Future<String> future = null;
  future = asyncService.asyncFunc();
  System.out.println(future.get());
  System.out.println(" The main thread is blocked and the execution is completed ");
 }

Execution results

async!
It took 2 seconds to send the message
Main thread execution completed


Related articles: