SpringBoot使用线程池处理耗时任务

场景分析

在post请求接口中,由于耗时任务处理时间过长,接口返回不可能一直等待业务逻辑处理完全才返回给前端,这时必须使用线程池来处理耗时任务,然后接口直接返回。通过异步处理的方式处理数据。

线程池选择

由于是SpringBoot项目,最终决定使用线程池ThreadPoolExecutor,可以利用Spring提供的对ThreadPoolExecutor封装的线程池ThreadPoolTaskExecutor,直接使用注解启用。

使用步骤

1、配置类编写
先创建一个线程池的配置,让SpringBoot加载,用来定义如何创建一个ThreadPoolTaskExecutor线程池,要使用 @Configuration 和@EnableAsync 这两个注解,表示这是个配置类,并且是线程池的配置类。

/**
 * @Author:hutao2
 * @Date: 2010/11/27 22:01
 */
@Configuration
@EnableAsync
public class ExecutorConfig {

    private static final Logger logger = LoggerFactory.getLogger(ExecutorConfig.class);
    //这里在配置文件(application.yml)中进行配置
    //本例中为了方便将配置写死了
    private int corePoolSize = 10;
   
    private int maxPoolSize = 10;
   
    private int queueCapacity = 99999;
    
    private String namePrefix = ocr-Thread-;

    @Bean(name = "asyncServiceExecutor")
    public Executor asyncServiceExecutor() {
        logger.info("start asyncServiceExecutor");
        //ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        ThreadPoolTaskExecutor executor = new VisiableThreadPoolTaskExecutor();//用自定义的子类,可以展示线程池的状况
        //配置核心线程数
        executor.setCorePoolSize(corePoolSize);
        //配置最大线程数
        executor.setMaxPoolSize(maxPoolSize);
        //配置队列大小
        executor.setQueueCapacity(queueCapacity);
        //配置线程池中的线程的名称前缀
        executor.setThreadNamePrefix(namePrefix);

        // rejection-policy:当pool已经达到max size的时候,如何处理新任务
        // CALLER_RUNS:不在新线程中执行任务,而是有调用者所在的线程来执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //执行初始化
        executor.initialize();
        return executor;
    }
}

2、ThreadPoolTaskExecutor的子类编写
为了展示线程池当时的情况,有多少线程在执行,多少在队列中等待,要创建了一个ThreadPoolTaskExecutor的子类,在每次提交线程的时候都会将当前线程池的运行状况打印出来。

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.util.concurrent.ListenableFuture;

import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @Author:hutao2
 * @Date: 2010/11/27 22:19
 */
public class VisiableThreadPoolTaskExecutor extends ThreadPoolTaskExecutor {

    private static final Logger logger = LoggerFactory.getLogger(VisiableThreadPoolTaskExecutor.class);

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

3、Service接口以及实现类(demo)
创建一个Service接口(异步线程执行的耗时操作)以及Service的实现类(ServiceImpl)

public interface AsyncService {
    /**
     * 执行异步任务
     * 可以根据需求,自己加参数拟定,我这里就做个测试演示
     */
    void executeAsync();
}

将Service层的服务异步化,在executeAsync()方法上增加注解@Async(“asyncServiceExecutor”),asyncServiceExecutor方法是前面ExecutorConfig.java中的方法名,表明executeAsync方法进入的线程池是asyncServiceExecutor方法创建的。

@Service
public class AsyncServiceImpl implements AsyncService {
    private static final Logger logger = LoggerFactory.getLogger(AsyncServiceImpl.class);

    @Override
    @Async("asyncServiceExecutor")
    public void executeAsync() {
        logger.info("start executeAsync");

        System.out.println("异步线程要做的事情");
        System.out.println("可以在这里执行批量插入等耗时的事情");

        logger.info("end executeAsync");
    }
}

4、在Controller里通过@Autowired注入上面的Service

@Autowired
private AsyncService asyncService;

@GetMapping("/async")
public void async(){
    asyncService.executeAsync();
}

5、使用测试工具发起请求观察控制台

2019-12-29 22:23:30.951  INFO 14088 --- [nio-8087-exec-2] u.d.e.e.i.VisiableThreadPoolTaskExecutor : ocr-Thread-, 2. do submit,taskCount [0], completedTaskCount [0], activeCount [0], queueSize [0]
2019-12-29 22:23:30.952  INFO 14088 --- [ocr-Thread-1] c.u.d.e.executor.impl.AsyncServiceImpl   : start executeAsync
异步线程要做的事情
可以在这里执行批量插入等耗时的事情
2019-12-29 22:23:30.953  INFO 14088 --- [ocr-Thread-1] c.u.d.e.executor.impl.AsyncServiceImpl   : end executeAsync
2019-12-29 22:23:31.351  INFO 14088 --- [nio-8087-exec-3] u.d.e.e.i.VisiableThreadPoolTaskExecutor : ocr-Thread-, 2. do submit,taskCount [1], completedTaskCount [1], activeCount [0], queueSize [0]
2019-12-29 22:23:31.353  INFO 14088 --- [ocr-Thread-2] c.u.d.e.executor.impl.AsyncServiceImpl   : start executeAsync
异步线程要做的事情
可以在这里执行批量插入等耗时的事情
2019-12-29 22:23:31.353  INFO 14088 --- [ocr-Thread-2] c.u.d.e.executor.impl.AsyncServiceImpl   : end executeAsync
2019-12-29 22:23:31.927  INFO 14088 --- [nio-8087-exec-5] u.d.e.e.i.VisiableThreadPoolTaskExecutor : ocr-Thread-, 2. do submit,taskCount [2], completedTaskCount [2], activeCount [0], queueSize [0]
2019-12-29 22:23:31.929  INFO 14088 --- [ocr-Thread-3] c.u.d.e.executor.impl.AsyncServiceImpl   : start executeAsync
异步线程要做的事情
可以在这里执行批量插入等耗时的事情
2019-12-29 22:23:31.930  INFO 14088 --- [ocr-Thread-3] c.u.d.e.executor.impl.AsyncServiceImpl   : end executeAsync
2019-12-29 22:23:32.496  INFO 14088 --- [nio-8087-exec-7] u.d.e.e.i.VisiableThreadPoolTaskExecutor : ocr-Thread-, 2. do submit,taskCount [3], completedTaskCount [3], activeCount [0], queueSize [0]
2019-12-29 22:23:32.498  INFO 14088 --- [ocr-Thread-4] c.u.d.e.executor.impl.AsyncServiceImpl   : start executeAsync
异步线程要做的事情
可以在这里执行批量插入等耗时的事情
2019-12-29 22:23:32.499  INFO 14088 --- [ocr-Thread-4] c.u.d.e.executor.impl.AsyncServiceImpl   : end executeAsync

说明

本次问题是在工作中处理文档识别中碰到的,记录一下线程池的使用。具体内容由于代码在内网环境中以及代码不能公开的原因,我就使用了一个网上的学习例子来记录。关键是能够使用线程池处理问题。
参考网站:SpringBoot线程池的使用

  • 6
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值