@Async 结合CompletableFuture使用

@Async含义:

  1. 在方法上使用此注解,申明该方法是一个异步任务
  2. 在类上使用此注解,申明该类中的方法都是异步任务
  3. 在使用此注解的类对象,必须为spring管理下的bean
  4. 想要使用此异步任务,需要在配置类上添加@EnableAsync注解

使用:

在Spring中启用@Async:

        1,@Async注解在使用时,如果不指定线程池的名称,则使用Spring默认的线程池,Spring默认的线程池为SimpleAsyncTaskExecutor。

        2,方法上一旦标记了这个@Async注解,当其它线程调用这个方法时,就会开启一个新的子线程去异步处理该业务逻辑。

代码示例:

  

复制代码
@Configuration
@EnableAsync
public class ThreadPoolConfig {

    @Bean("fileTaskExecutor")
    public TaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 设置核心线程数 8
        executor.setCorePoolSize(8);
        // 设置最大线程数 16
        executor.setMaxPoolSize(16);
        // 设置队列容量 1000
        executor.setQueueCapacity(500);
        // 设置线程活跃时间(秒)
        executor.setKeepAliveSeconds(60);
        // 设置默认线程名称
        executor.setThreadNamePrefix("myThread-");
        // 设置拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 等待所有任务结束后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.initialize();
        return executor;
    }
}
复制代码
复制代码
@Service
public class MyAsyncTask {
     @Async("fileTaskExecutor") //使用自定义的线程池(执行器)
    public CompletableFuture<MyTask> asyncCpsItemImportTask(Sting value){
      Task task = new MyTask();  
        //...具体业务逻辑
    return CompletableFuture.completedFuture(task);
    }
}
复制代码

如何调用:

复制代码
@Service
public class LogService{
     
    public void asyncCpsItemImportTask(String value){
      List<CompletableFuture<MyTask>> result = new ArrayList<>();
        //...具体业务逻辑
    result.forEach(future -> {
           MyTask my =future.get();
         //....具体业务
        }
    }
}        
复制代码

 

posted @   KeepSmiling_me  阅读(224)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示