spring boot 异步开发

Spring Boot 提供了多种异步开发的方式,以下是其中几种常用的方法:

  1. 使用 @Async 注解

在 Spring Boot 中,可以使用 @Async 注解来声明一个方法是异步的。需要在启动类或者配置类上添加 @EnableAsync 注解以启用异步支持。

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. 使用 TaskExecutor

除了使用 @Async 注解,还可以使用 TaskExecutor 来手动执行异步任务。可以在配置类中创建一个 TaskExecutor Bean,然后在需要执行异步任务的地方使用它。

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. 使用 CompletableFuture

Spring Boot 还提供了 CompletableFuture 类,可以用来执行异步任务并获取结果。CompletableFuture 是 Java 8 引入的,Spring Boot 也提供了对它的支持。

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;
    }
}

猜你喜欢

转载自blog.csdn.net/m0_61581389/article/details/132561536