springboot使用@Async实现异步操作

个人感觉,@Asyn和@scheduled是springboot对jdk中ThreadpoolExecutor和ScheduledThreadpoolExecutor的再次封装。它们在springboot中分别是ThreadPoolTaskExecutor和ThreadPoolTaskScheduled.

使用方法

  1. 创建配置类,实现AsyncConfigurer接口,实现方法getAsyncExecutor(),
  2. 自定义线程池。默认情况下ThreadPoolTaskExecutor是只有一个线程的,所以要自定义线程池。
  3. 同时可以定义多个线程池,有任务时可以使用不同线程池中的线程。
  4. 使用@EnableAsync注解标注类,开启Async功能。
package com.example.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

@Configuration
@EnableAsync
public class TaskExecutorConfig implements AsyncConfigurer {
   


    @Override
    public Executor getAsyncExecutor() {
   

        /*
        默认值
        private int corePoolSize = 1;
        private int maxPoolSize = Integer.MAX_VALUE;
        private int queueCapacity = Integer.MAX_VALUE;
         */
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        taskExecutor.setCorePoolSize(10);
        taskExecutor.setMaxPoolSize(20);
        taskExecutor.setQueueCapacity(10);
        taskExecutor.initialize();
        return taskExec
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值