天天看點

SpringBoot異步任務(多線程)配置類使用結果注意事項

配置類

@Configuration
@EnableAsync
public class AsyncConfig implements AsyncConfigurer {

	@Override
	public Executor getAsyncExecutor() {
		ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
		// 核心線程池數量,方法;
		executor.setCorePoolSize(7);
		// 最大線程數量
		executor.setMaxPoolSize(42);
		// 線程池的隊列容量
		executor.setQueueCapacity(11);
		// 線程名稱的字首
		executor.setThreadNamePrefix("fyk-executor-");
		// 線程池對拒絕任務的處理政策
		executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
		executor.initialize();
		return executor;
	}

	@Override
	public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
		return new SimpleAsyncUncaughtExceptionHandler();
	}
}
           

@EnableAsync:表示的是開啟異步任務(多線程)功能;

拒絕政策常用有有這四種:

  • ThreadPoolExecutor.AbortPolicy:丢棄任務并抛出RejectedExecutionException異常(預設);
  • ThreadPoolExecutor.DiscardPolic:丢棄任務,但是不抛出異常;
  • ThreadPoolExecutor.DiscardOldestPolicy:丢棄隊列最前面的任務,然後重新嘗試執行任務;
  • ThreadPoolExecutor.CallerRunsPolic:由調用線程處理該任務;

多個線程池

在配置類中,ThreadPoolTaskExecutor類是一個線程池。我們配置了一些線程池的參數。如果在使用異步任務的時候,想使用額外的線程池,也就是說,配置多個線程池:

@Configuration
public class TaskExecutorConfig {
	@Bean("taskExecutor2")
	public ThreadPoolTaskExecutor taskExecutor2() {
		ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
		// 核心線程數(預設線程數)
		executor.setCorePoolSize(10);
		// 最大線程數
		executor.setMaxPoolSize(40);
		// 緩沖隊列數
		executor.setQueueCapacity(10);
		// 允許線程空閑時間(機關:預設為秒)
		executor.setKeepAliveSeconds(10);
		// 線程名稱的字首
		executor.setThreadNamePrefix("fyk-executor2-");
		// 線程池對拒絕任務的處理政策
		executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
		// 初始化
		executor.initialize();
		return executor;
	}
}
           

這個時候,在使用的時候,如果@Async(“taskExecutor2”),則隻用的是taskExecutor2線程池。

使用

使用方式和簡單,在需要開啟線程的方法或者類類上,加上注解:@Async

@Component
@Slf4j
public class Test {

	@Async
	@Scheduled(fixedDelay = 10000)
	public void handle() {
		log.info("fixedDelay-每間隔多少毫秒執行一次(這個時間間隔是:最後一次調用結束和下一次調用開始之間)!");
	}
	
	@Async("taskExecutor2")
	@Scheduled(fixedRate = 10000)
	public void handle2() {
		log.info("fixedRate-每間隔多少毫秒執行一次!");
	}
}
           

至此,已經算完成了。

結果

SpringBoot異步任務(多線程)配置類使用結果注意事項

從這個線程池的名字中,可以看到,分别使用的是兩個線程池。

注意事項

如下方式會使@Async失效

  • 異步方法使用static修飾

繼續閱讀