SpingBoot异步执行多线程配置方式,有2种方式。
方式1.利用java的线程池Executor
第一步:需要在项目中启用异步支持,在启动类加上@EnableAsync注解
第二步:写一个配置类,类上面要加@Configuration注解。配置如下:
- @Bean("myAsync")public Executor myAsync() {
- ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
- executor.setCorePoolSize(5);
- executor.setMaxPoolSize(10);
- executor.setQueueCapacity(100);
- executor.setThreadNamePrefix("ShopService-");
- executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
- executor.initialize();
- return executor;
- }
第三步:是在需要使用异步的方法或者类上面加注解@Async即可
方式2.使用ExecutorService来实现,方法如下:
第一步:写一个配置类,类上面要加@Configuration注解。配置如下:
- @Bean
- public ThreadPoolExecutorFactoryBean shopPayExecutorFactoryBean() {
- ThreadPoolExecutorFactoryBean executorFactoryBean = new ThreadPoolExecutorFactoryBean();
- executorFactoryBean.setCorePoolSize(10);
- executorFactoryBean.setMaxPoolSize(100);
- executorFactoryBean.setQueueCapacity(300);
- executorFactoryBean.setThreadNamePrefix("shop-pay-");
- executorFactoryBean.setWaitForTasksToCompleteOnShutdown(true);
- executorFactoryBean.setAwaitTerminationSeconds(500);
- return executorFactoryBean;
- }
- @Bean(name = "executorService")
- public ExecutorService shopPayExecutor() {
- return shopPayExecutorFactoryBean().getObject();
- }
第二步:在需要使用的类自动注入ExevutorService,然后使用其execute方法来执行。如下:
- @Autowired
- ExecutorService executorService;@Test
- public void executorServiceTest() {
- executorService.execute(() -> System.out.println("NOW:" + Thread.currentThread().getName()));
- }