Implementation of asynchronous call to springboot

  • 2021-07-18 08:05:16
  • OfStack

Before talking about asynchronous call, let's talk about its corresponding synchronous call. Usually, in the development process, we all call synchronously, that is, the program executes in sequence according to the defined order, and the execution process of each line of code must wait for the execution of the previous line of code before execution. The asynchronous call means that when the program is executing, it can continue to execute the following code without waiting for the return value of execution. Obviously, synchronization has dependency dependencies, while asynchronism does not, so asynchronism can be executed concurrently, which can improve execution efficiency and do more things at the same time.

Synchronization

Programs are executed in the defined order, and every line of programs must wait for the last line of programs to be executed, that is, when a function call is issued, the call will not return before the result is obtained.

Asynchronous

When a program is executed sequentially, it executes the following program without waiting for the statement called asynchronously to return the result. When an asynchronous procedure call is issued, the caller cannot get the result immediately.

Synchronization code

Service Layer:


public void test() throws InterruptedException {
    Thread.sleep(2000);
    for (int i = 0; i < 1000; i++) {
      System.out.println("i = " + i);
    }
  }

Controller Layer:


  @GetMapping("test")
  public String test() {
    try {
      Thread.sleep(1000);
      System.out.println(" Main thread starts ");
      for (int j = 0; j < 100; j++) {
        System.out.println("j = " + j);
      }
      asyncService.test();
      System.out.println(" End of main thread ");
      return "async";
    } catch (InterruptedException e) {
      e.printStackTrace();
      return "fail";
    }
  }

Request http://localhost: 8080/test in browser

Console print sequence:

Main thread starts Print j Loop Print i Loop End of main thread

Asynchronous code

Annotate @ Async on the test method in the Service layer, and annotate @ EnableAsync on the startup class for asynchronous effect

Service Layer:


 @Async
  public void test() throws InterruptedException {
    Thread.sleep(2000);
    for (int i = 0; i < 1000; i++) {
      System.out.println("i = " + i);
    }
  }

Controller unchanged, startup class plus @ EnableAsync:


@SpringBootApplication
@EnableAsync
public class AsyncApplication {
  public static void main(String[] args) {
    SpringApplication.run(AsyncApplication.class, args);
  }
}

Request printing again in the following order:

Main thread starts Print j Loop End of main thread Print i Loop

Code: async


Related articles: