前言

前两天做我的项目的时候,想进步一下插入表的性能优化,因为是两张表,先插旧的表,紧接着插新的表,一万多条数据就有点慢了

前面就想到了线程池ThreadPoolExecutor,而用的是Spring Boot我的项目,能够用Spring提供的对ThreadPoolExecutor封装的线程池ThreadPoolTaskExecutor,间接应用注解启用

应用步骤

先创立一个线程池的配置,让Spring Boot加载,用来定义如何创立一个ThreadPoolTaskExecutor,要应用@Configuration和@EnableAsync这两个注解,示意这是个配置类,并且是线程池的配置类。

Spring Boot 根底就不介绍了,系列教程和示例源码看这里:https://github.com/javastacks...

更多 Spring Boot 教程能够微信搜寻Java技术栈在后盾发送 boot 进行浏览,我都整顿好了。

@Configuration@EnableAsyncpublic class ExecutorConfig {    private static final Logger logger = LoggerFactory.getLogger(ExecutorConfig.class);    @Value("${async.executor.thread.core_pool_size}")    private int corePoolSize;    @Value("${async.executor.thread.max_pool_size}")    private int maxPoolSize;    @Value("${async.executor.thread.queue_capacity}")    private int queueCapacity;    @Value("${async.executor.thread.name.prefix}")    private String namePrefix;    @Bean(name = "asyncServiceExecutor")    public Executor asyncServiceExecutor() {        logger.info("start asyncServiceExecutor");        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();        //配置外围线程数        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;    }}

@Value是我配置在application.properties,能够参考配置,自在定义

# 异步线程配置# 配置外围线程数async.executor.thread.core_pool_size = 5# 配置最大线程数async.executor.thread.max_pool_size = 5# 配置队列大小async.executor.thread.queue_capacity = 99999# 配置线程池中的线程的名称前缀async.executor.thread.name.prefix = async-service-

创立一个Service接口,是异步线程的接口

public interface AsyncService {    /**     * 执行异步工作     * 能够依据需要,本人加参数拟定,我这里就做个测试演示     */    void executeAsync();}

实现类

@Servicepublic 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");    }}

将Service层的服务异步化,在executeAsync()办法上减少注解@Async("asyncServiceExecutor"),asyncServiceExecutor办法是后面ExecutorConfig.java中的办法名,表明executeAsync办法进入的线程池是asyncServiceExecutor办法创立的。

接下来就是在Controller里或者是哪里通过注解@Autowired注入这个Service

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

用postmain或者其余工具来屡次测试申请一下

 2018-07-16 22:15:47.655  INFO 10516 --- [async-service-5] c.u.d.e.executor.impl.AsyncServiceImpl   : start executeAsync异步线程要做的事件能够在这里执行批量插入等耗时的事件2018-07-16 22:15:47.655  INFO 10516 --- [async-service-5] c.u.d.e.executor.impl.AsyncServiceImpl   : end executeAsync2018-07-16 22:15:47.770  INFO 10516 --- [async-service-1] c.u.d.e.executor.impl.AsyncServiceImpl   : start executeAsync异步线程要做的事件能够在这里执行批量插入等耗时的事件2018-07-16 22:15:47.770  INFO 10516 --- [async-service-1] c.u.d.e.executor.impl.AsyncServiceImpl   : end executeAsync2018-07-16 22:15:47.816  INFO 10516 --- [async-service-2] c.u.d.e.executor.impl.AsyncServiceImpl   : start executeAsync异步线程要做的事件能够在这里执行批量插入等耗时的事件2018-07-16 22:15:47.816  INFO 10516 --- [async-service-2] c.u.d.e.executor.impl.AsyncServiceImpl   : end executeAsync2018-07-16 22:15:48.833  INFO 10516 --- [async-service-3] c.u.d.e.executor.impl.AsyncServiceImpl   : start executeAsync异步线程要做的事件能够在这里执行批量插入等耗时的事件2018-07-16 22:15:48.834  INFO 10516 --- [async-service-3] c.u.d.e.executor.impl.AsyncServiceImpl   : end executeAsync2018-07-16 22:15:48.986  INFO 10516 --- [async-service-4] c.u.d.e.executor.impl.AsyncServiceImpl   : start executeAsync异步线程要做的事件能够在这里执行批量插入等耗时的事件2018-07-16 22:15:48.987  INFO 10516 --- [async-service-4] c.u.d.e.executor.impl.AsyncServiceImpl   : end executeAsync

通过以上日志能够发现,[async-service-]是有多个线程的,显然曾经在咱们配置的线程池中执行了,并且每次申请中,controller的起始和完结日志都是间断打印的,表明每次申请都疾速响应了,而耗时的操作都留给线程池中的线程去异步执行;

尽管咱们曾经用上了线程池,然而还不分明线程池过后的状况,有多少线程在执行,多少在队列中期待呢?这里我创立了一个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: ChenBin */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);    }}

如上所示,showThreadPoolInfo办法中将工作总数、已实现数、沉闷线程数,队列大小都打印进去了,而后Override了父类的execute、submit等办法,在外面调用showThreadPoolInfo办法,这样每次有工作被提交到线程池的时候,都会将以后线程池的根本状况打印到日志中;

批改ExecutorConfig.java的asyncServiceExecutor办法,将ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor()改为ThreadPoolTaskExecutor executor = new VisiableThreadPoolTaskExecutor()

@Bean(name = "asyncServiceExecutor")public Executor asyncServiceExecutor() {    logger.info("start asyncServiceExecutor");    //在这里批改    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;}

再次启动该工程测试

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

留神这一行日志:

2018-07-16 22:23:32.496  INFO 14088 --- [nio-8087-exec-7] u.d.e.e.i.VisiableThreadPoolTaskExecutor : async-service-, 2. do submit,taskCount [3], completedTaskCount [3], activeCount [0], queueSize [0]

这阐明提交工作到线程池的时候,调用的是submit(Callable task)这个办法,以后曾经提交了3个工作,实现了3个,以后有0个线程在解决工作,还剩0个工作在队列中期待,线程池的根本状况一路了然;

原文链接:https://blog.csdn.net/m0_3770...

版权申明:本文为CSDN博主「如漩涡」的原创文章,遵循CC 4.0 BY-SA版权协定,转载请附上原文出处链接及本申明。

近期热文举荐:

1.600+ 道 Java面试题及答案整顿(2021最新版)

2.终于靠开源我的项目弄到 IntelliJ IDEA 激活码了,真香!

3.阿里 Mock 工具正式开源,干掉市面上所有 Mock 工具!

4.Spring Cloud 2020.0.0 正式公布,全新颠覆性版本!

5.《Java开发手册(嵩山版)》最新公布,速速下载!

感觉不错,别忘了顺手点赞+转发哦!