首页 > 编程语言 > 详细

【框架】SpringBoot中自定义线程池

时间:2021-01-18 14:33:33      阅读:330      评论:0      收藏:0      [点我收藏+]

自定义线程池

SpringBoot中对线程池的自定义分为两种:

  1. 修改默认的线程池
  2. 创建新的自定义线程池

1. 修改默认的线程池

修改默认的线程池,需要创建配置类:

  1. 加入两个注解:
    1. @EnableAsync 开启异步执行功能
    2. @Configuration Spring配置类
  2. 实现AsyncConfigurer接口,并实现两个方法:
    1. public Executor getAsyncExecutor():注意在返回Executor必须初始化executor.initialize()
    2. public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler()
/** 修改默认线程池 */
@Slf4j
@EnableAsync
@Configuration
public class AsyncPoolConfig implements AsyncConfigurer {
    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //核心线程池大小
        executor.setCorePoolSize(10);
        //最大线程数
        executor.setMaxPoolSize(20);
        //队列容量
        executor.setQueueCapacity(20);
        //活跃时间
        executor.setKeepAliveSeconds(60);
        //线程名字前缀
        executor.setThreadNamePrefix("AsyncPool_");
        // 拒绝策略
        executor.setRejectedExecutionHandler(
                new ThreadPoolExecutor.CallerRunsPolicy()
        );
        // 停机是否等待任务
        executor.setWaitForTasksToCompleteOnShutdown(true);
        // 停机等待任务的最大时长
        executor.setAwaitTerminationSeconds(60);
        
        // 线程池初始化
        executor.initialize();
        return executor;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new AsyncUncaughtExceptionHandler(){
            @Override
            public void handleUncaughtException(Throwable throwable,
                                                Method method,
                                                Object... objects) {
                throwable.printStackTrace();
                log.error("AsyncError: {}, Method: {}",
                        throwable.getMessage(), method.getName()
            }
        };
    }
}

2. 创建新的自定义线程池

直接在Spring配置类中创建返回Executor的方法,并加上@Bean注解注册为Bean。

@Configuration
public class MyAsyncPool {
    @Bean
    public Executor MyAsyncPool() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //核心线程池大小
        executor.setCorePoolSize(10);
        //最大线程数
        executor.setMaxPoolSize(20);
        //队列容量
        executor.setQueueCapacity(20);
        //活跃时间
        executor.setKeepAliveSeconds(60);
        //线程名字前缀
        executor.setThreadNamePrefix("MyAsyncPool_");
        // 拒绝策略
        executor.setRejectedExecutionHandler(
                new ThreadPoolExecutor.CallerRunsPolicy()
        );
        // 停机是否等待任务
        executor.setWaitForTasksToCompleteOnShutdown(true);
        // 停机等待任务的最大时长
        executor.setAwaitTerminationSeconds(60);

        executor.initialize();
        return executor;
    }
}

线程池的使用

在需要开启异步执行的方法上,加入两个注解:

  1. @Scheduled(fixedRate = 3*1000) fixedRate单位为毫秒
  2. @Async(value)开启异步执行,这里的参数分为几种情况:
    1. 不填 或 "":采用默认的线程池,如果修改过默认线程池,则使用修改过的配置
    2. "taskScheduler":无论是否修改过默认线程池,都使用修改前的默认配置
    3. 自定义线程池类名:使用指定的自定义线程池,注意这里是类名(即注册为Bean的名字)
@Slf4j
@Component
public class Task {
    @Scheduled(fixedRate = 3*1000)
    @Async("MyAsyncPool")
    public void cleanExpiredTemplate_(){
        log.info(Thread.currentThread().getName() + ": Task is finished");
    }
}

【框架】SpringBoot中自定义线程池

原文:https://www.cnblogs.com/BWSHOOTER/p/14292200.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!