SpringBoot异步Async处理

  1. SpringApplication开启Async
@Slf4j
@EnableAsync
@SpringBootApplication
public class CommonApplication {

    public static void main(String[] args) {
        log.info("application start...");
        SpringApplication.run(CommonApplication.class, args);
    }

}
  1. 配置线程池参数
使用spring自带线程池ThreadPoolTaskExecutor处理异步任务
@Configuration
@Slf4j
public class AsyncConfig {

    private ThreadPoolTaskExecutor taskExecutor;

    /**
     * spring 自带线程池
     * @return
     */
    @Bean("taskExecutor")
    public Executor taskExecutor(){
        ThreadPoolTaskExecutor  taskExecutor = new ThreadPoolTaskExecutor();
        // 核心线程数
        taskExecutor.setCorePoolSize(10);
        // 最大线程数
        taskExecutor.setMaxPoolSize(20);
        // 队列容量
        taskExecutor.setQueueCapacity(100);
        // 线程空闲时间
        taskExecutor.setKeepAliveSeconds(60);
        // 线程名前缀
        taskExecutor.setThreadNamePrefix("taskExecutor-");
        // 用来设置线程池关闭的时候等待所有任务都完成再继续销毁其他的Bean,这样这些异步任务的销毁就会先于Redis线程池的销毁
        taskExecutor.setWaitForTasksToCompleteOnShutdown(true);
        // 设置线程池中任务的等待时间,如果超过这个时候还没有销毁就强制销毁,以确保应用最后能够被关闭,而不是阻塞住
        taskExecutor.setAwaitTerminationSeconds(60);
        // 拒绝策略
        taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        return taskExecutor;
    }

}
  1. 编写异步逻辑
/**
 * 异步工具处理
 */
@Service
public class AsyncUtils {

    @Async("taskExecutor")
    public void doTask() throws InterruptedException {
    	Thread.sleep(10000);
        System.out.println("处理任务");
    }
}
  1. 调用示例(异步处理方法和业务逻辑方法不能在同一个类中)
@Service
@Slf4j
public class AsyncServiceImpl implements AsyncService {

    @Autowired
    private AsyncUtils asyncUtils;

    @Override
    public void doWork() {
        try {
            System.out.println("开始工作");
            // 调用异步方法
            asyncUtils.doTask();
            System.out.println("结束工作");
        } catch (InterruptedException e) {
            log.error("thread error");
        }
    }
}
  1. 结果符合预期
    在这里插入图片描述
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值