Spring线程池ThreadPoolTaskExecutor使用

时间:2021-09-17
本文章向大家介绍Spring线程池ThreadPoolTaskExecutor使用,主要包括Spring线程池ThreadPoolTaskExecutor使用使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

创建线程池

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

原文地址:https://www.cnblogs.com/JNU-Iot-Longxin/p/15305050.html