利用 spring @Async 注解 开启异步 线程池处理任务

1.

import com.alibaba.dubbo.common.logger.Logger;
import com.alibaba.dubbo.common.logger.LoggerFactory;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
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.lang.reflect.Method;
import java.util.concurrent.Executor;

/**
 * 开启异步任务支持
 */

@EnableAsync //开启异步任务支持
@Configuration
//@ComponentScan("当前包路径") 如果spring 已经配置扫描改目录了,该配置可以忽略
public class TaskExecutorConfig implements AsyncConfigurer {

    private static final Logger logger = LoggerFactory.getLogger(TaskExecutorConfig.class);
    //  异步调用线程池大小 可灵活配置,默认获取服务器cpu个数
    public static Integer smsAsynSize = Runtime.getRuntime().availableProcessors();

    @Override
    public Executor getAsyncExecutor() {
        logger.info(">>>>>>>>>>>>>>>初始化异步任务支持开始<<<<<<<<<<<<<<<<<");
        ThreadPoolTaskExecutor  taskExecutor = new ThreadPoolTaskExecutor();
        taskExecutor.setCorePoolSize(smsAsynSize);
        taskExecutor.setMaxPoolSize(smsAsynSize*2);
        taskExecutor.setQueueCapacity(smsAsynSize*5);
        taskExecutor.setThreadNamePrefix("SpringAsyncThread-");
        taskExecutor.initialize();
        logger.info(">>>>>>>>>>>>>>>初始化异步任务支持结束<<<<<<<<<<<<<<<<<");
        return taskExecutor;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new SimpleAsyncUncaughtExceptionHandler();
    }

    class  SimpleAsyncUncaughtExceptionHandler  implements AsyncUncaughtExceptionHandler{

        @Override
        public void handleUncaughtException(Throwable throwable, Method method, Object... objects) {
            logger.error("异步回调失败了, exception message : " + throwable.getMessage());
        }
    }
}

 

2.  只需在对应的方法上加上 @Async 注解 即可

import org.junit.Test;
import org.springframework.scheduling.annotation.Async;

/**
 * 开启spring 异步
 */
public class TaskExecutorTest extends  TestService {

    @Test
    public  void test() {
        TaskExecutorTest taskExecutorTest = new TaskExecutorTest();
        for (int i = 0 ;i< 10;i++){
            taskExecutorTest.executeAsyncTask(i);
            taskExecutorTest.executeAsyncTaskPlus(i);
        }

    }

    @Async
    public  void executeAsyncTask(Integer i){
        System.out.println("执行异步任务"+i);
    }

    @Async
    public void executeAsyncTaskPlus(Integer i){
        System.out.println("执行异步任务+1:"+(i+1));
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

潇凝子潇

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值