SpringBoot配置ThreadPoolExecutor多线程

本文介绍了使用ThreadPoolExecutor提供的线程池服务,借助Spring Boot框架的@Async注解将业务逻辑异步执行的实战过程。包括编写多线程配置类、controller请求、service实现,解决可能出现的报错,扩展ThreadPoolTaskExecutor类以监控线程池状况,最后启动项目验证线程。

我们常用ThreadPoolExecutor提供的线程池服务,SpringBoot框架提供了@Async注解,帮助我们更方便的将业务逻辑提交到线程池中异步执行,今天我们就来实战体验这个线程池服务。

  1. 编写多线程配置类
 @EnableAsync
@Configuration
public class ThreadExecutorConfig {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Bean
    public Executor taskExecutor() {
        logger.info("start taskExecutor");
        ThreadPoolTaskExecutor executor = new VisiableThreadPoolTaskExecutor();
        //配置核心线程数
        executor.setCorePoolSize(5);
        //设置最大线程数
        executor.setMaxPoolSize(10);
        //设置队列容量
        executor.setQueueCapacity(20);
        //设置线程活跃时间(秒)
        executor.setKeepAliveSeconds(60);
        //配置线程池中的线程的名称前缀
        executor.setThreadNamePrefix("async-ews-service-");
        //设置拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //等待所有任务结束后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        //执行初始化
        executor.initialize();
        return executor;
    }
}

java.util.concurrent.TaskExecutor或其子类的bean,并在配置类或直接在程序入口类上声明注解@EnableAsync。

  1. 编写controller请求
 @GetMapping(value = "getDemo")
    public void getDemo() throws InterruptedException {
        redisService.getDemo();
        logger.info("22222222222222222222" + redisService.redisGet(0, "abc-1"));
        logger.info("6566666666666666");
        logger.info("33333333333333333333" + redisService.redisGet(1, "abc-1234.phli"));
    }
  1. 编写service实现,给服务添加异步注解@Async
void getDemo() throws InterruptedException;
@Async
    @Override
    public void getDemo() throws InterruptedException {
        Thread.sleep(5000);
        logger.info("this is thread!");
    }

这儿可能会有坑,报错:Null return value from advice does not match primitive return type for错误,用void没有该错误信息。
4. 扩展ThreadPoolTaskExecutor类
虽然我们已经用上了线程池,但是还不清楚线程池当时的情况,有多少线程在执行,多少在队列中等待呢?这里我创建了一个ThreadPoolTaskExecutor的子类,在每次提交线程的时候都会将当前线程池的运行状况打印出来。

 public class VisiableThreadPoolTaskExecutor extends ThreadPoolTaskExecutor {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private void showThreadPoolInfo(String prefix){
        ThreadPoolExecutor threadPoolExecutor = getThreadPoolExecutor();
        if(null == threadPoolExecutor){
            return;
        }

        logger.info("{}{},taskCount [{}], completedTaskCount [{}], activeCount [{}], queueSize [{}]",
                this.getThreadNamePrefix(),
                prefix,
                threadPoolExecutor.getTaskCount(),
                threadPoolExecutor.getCompletedTaskCount(),
                threadPoolExecutor.getActiveCount(),
                threadPoolExecutor.getQueue().size());
    }

    @Override
    public void execute(Runnable task) {
        showThreadPoolInfo("1. do execute");
        super.execute(task);
    }

    @Override
    public void execute(Runnable task, long startTimeout) {
        showThreadPoolInfo("2. do execute");
        super.execute(task, startTimeout);
    }

    @Override
    public Future<?> submit(Runnable task) {
        showThreadPoolInfo("1. do submit");
        return super.submit(task);
    }

    @Override
    public <T> Future<T> submit(Callable<T> task) {
        showThreadPoolInfo("2. do submit");
        return super.submit(task);
    }

    @Override
    public ListenableFuture<?> submitListenable(Runnable task) {
        showThreadPoolInfo("1. do submitListenable");
        return super.submitListenable(task);
    }

    @Override
    public <T> ListenableFuture<T> submitListenable(Callable<T> task) {
        showThreadPoolInfo("2. do submitListenable");
        return super.submitListenable(task);
    }
}

showThreadPoolInfo方法中将任务总数、已完成数、活跃线程数,队列大小都打印出来了。重写了父类的execute、submit等方法。在里面调用showThreadPoolInfo方法,这样每次有任务被提交到线程池的时候,都会将当前线程池的基本情况打印到日志中。

这个时候我们还要修改ThreadExecutorConfig类里面ThreadPoolTaskExecutor。将ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor()改为ThreadPoolTaskExecutor executor = new VisiableThreadPoolTaskExecutor()。

  1. 启动项目,请求接口,验证线程

在这里插入图片描述
6. 整理完毕!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

冰红茶不会渴

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

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

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

打赏作者

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

抵扣说明:

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

余额充值