利用 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));
    }

}

猜你喜欢

转载自blog.csdn.net/xu990128638/article/details/81662265