spring boot asynchronous development

Spring Boot provides a variety of asynchronous development methods, the following are some of the commonly used methods:

  1. Use @Async annotation

In Spring Boot, you can use the @Async annotation to declare a method to be asynchronous. The @EnableAsync annotation needs to be added to the startup class or configuration class to enable asynchronous support.

import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@EnableAsync
@Service
public class MyService {
    
    

    @Async
    public void doSomething() {
    
    
        // 这里是异步任务代码...
    }
}
  1. Using TaskExecutor

In addition to using the @Async annotation, you can also use TaskExecutor to manually execute asynchronous tasks. You can create a TaskExecutor Bean in the configuration class and then use it wherever you need to perform asynchronous tasks.

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.SimpleAsyncTaskExecutor;

@Configuration
public class TaskExecutorConfig {
    
    

    @Bean(name = "taskExecutor")
    public SimpleAsyncTaskExecutor taskExecutor() {
    
    
        return new SimpleAsyncTaskExecutor();
    }
}
  1. Using CompletableFuture

Spring Boot also provides the CompletableFuture class, which can be used to perform asynchronous tasks and obtain results. CompletableFuture was introduced in Java 8, and Spring Boot also provides support for it.

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.springframework.stereotype.Service;

@Service
public class MyService {
    
    

    public CompletableFuture<String> doSomethingAsync() throws InterruptedException, ExecutionException, TimeoutException {
    
    
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
    
    
            // 这里是异步任务代码...
            return "Hello World!";
        });
        return future;
    }
}

Guess you like

Origin blog.csdn.net/m0_61581389/article/details/132561536