springboot中如何使用執行緒池及非同步執行緒
阿新 • • 發佈:2019-02-20
有一些業務需求,需要是非同步進行的,不能影響當前執行緒的執行,在spring boot中則能通過註解和配置快速實現這個。
首先寫個非同步執行緒池配置類,如下:
@Configuration
@EnableAsync
public class AsyncConfig {
@Value("${async.executor.thread.core_pool_size}")
private int corePoolSize;
@Value("${async.executor.thread.max_pool_size}")
private int maxPoolSize;
@Value ("${async.executor.thread.queue_capacity}")
private int queueCapacity;
private String threadNamePrefix = "AsyncExecutorThread-";
@Bean(name = "asyncExecutor")
public Executor asyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(corePoolSize);
executor.setMaxPoolSize(maxPoolSize);
executor.setQueueCapacity(queueCapacity);
executor.setThreadNamePrefix(threadNamePrefix);
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
executor.initialize();
return executor;
}
}
然後將需要非同步執行的業務步驟寫成方法用@sync註解即可,如下:
@Component
public class AsyncExecutorCommon {
@Async("asyncExecutor")
public void loadPic(IfcTingshenJzml tsJzml,
WsTingshenJzmlService wsTingshenJzmlService) {
List<IfcTingshenJzml> tsJzmls = new ArrayList<IfcTingshenJzml>();
tsJzmls.add(tsJzml);
wsTingshenJzmlService.docService(tsJzmls);
}
}
在業務程式碼裡直接呼叫這個方法即可,這個方法的執行就是非同步的。注意,非同步方法和呼叫非同步的方法不能寫在一個類裡,否則會報迴圈依賴異常,建議另建一個類,只用來放非同步方法。