Spring线程池ThreadPoolTaskExecutor使用

 2022-09-11
原文地址:https://blog.51cto.com/u_15049782/4030546

创建线程池

    import lombok.extern.slf4j.Slf4j;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
     
    import java.util.concurrent.Executor;
    import java.util.concurrent.ThreadPoolExecutor;
     
    /**
     * @description: LizzThreadPoolTaskExecutor
     * @author: lizz
     */
    @Configuration
    @Slf4j
    public class LizzThreadPoolTaskExecutor {
        /**
         * @return
         */
        @Bean("lizzThreadExecutor")
        public Executor asyncServiceExecutor() {
            ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
            executor.setBeanName("lizzPool");
            executor.setCorePoolSize(4);//配置核心线程数
            executor.setMaxPoolSize(8);//配置最大线程数
            executor.setKeepAliveSeconds(30);
            executor.setQueueCapacity(100);//配置队列大小
            executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());//拒绝策略
            executor.setWaitForTasksToCompleteOnShutdown(true);
            executor.initialize();//执行初始化
            log.info("ThreadPool init success");
            return executor;
        }
    }

使用

    @Slf4j
    @RestController
    public class LizzController{
        @Autowired
        @Qualifier("lizzThreadExecutor")
        private Executor threadPool;
     
        @RequestMapping("go")
        public String go() {
                    log.info("controller go")
                    threadPool.execute(new Runnable() {
                        @Override
                        public void run() {
                  //业务代码
                            try {
                                log.info("threadPool go")
                            } catch (Exception e) {
                                log.error("into db type:{},key:{},encryptValue:{};",
                                        type, key, encryptValue, e);
                            }
                        }
                    });
     
        }
     
    }

控制台输出

    [nio-8070-exec-1] c.l.f.c.s.controller.LizzController      : controller go
    [     lizzPool-1] c.l.f.c.s.controller.LizzController      : threadPool go