spring boot 線程池

spring boot線程池有多種寫法,主要在配置方面,其實都差不多,現在列舉其中一種寫法

直接在啓動類配置

@SpringBootApplication
@EnableAsync
@ComponentScan("com.text")
public class DemoApplication {
    private int corePoolSize;
    private int maxPoolSize;
    private int queueCapacity;
    private String namePrefix;
    private int keepAliveTime;

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

    @Bean(name = "threadPool1")//name用於區分線程池
    public Executor asyncServiceExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //配置核心線程數
        executor.setCorePoolSize(corePoolSize = 5);
        //配置最大線程數
        executor.setMaxPoolSize(maxPoolSize = 20);
        //配置隊列大小
        executor.setQueueCapacity(queueCapacity = 200);
        //配置線程池中的線程的名稱前綴
        executor.setThreadNamePrefix(namePrefix ="thread_pool_1");
        //配置線程池最大空閒時間  秒
        executor.setKeepAliveSeconds(keepAliveTime=60);
        // CALLER_RUNS:不在新線程中執行任務,而是有調用者所在的線程來執行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //執行初始化
        executor.initialize();
        return executor;
    }

}

服務消費方

@RestController
public class Hello {

    @Autowired
    private HelloService helloService;

    @RequestMapping("hello")
    public void hello (){
        System.out.println("777");
        helloService.say();
        System.out.println("555");
    }
}

服務提供方

@Component
public class HelloService {

    @Async("threadPool1")
    public void say(){
        try{
            Thread.sleep(1000);
        }catch(Exception e){
            e.printStackTrace();
        }
        System.out.println("666");
    }
}

運行結果:

777
555
666

搞定,想配置多個線程池同理新增一個,只要把@bean裏面的name改一個名字,然後在@Async中指定線程池

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章