有一些业务需求,需要是异步进行的,不能影响当前线程的运行,在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);
}
}
在业务代码里直接调用这个方法即可,这个方法的执行就是异步的。注意,异步方法和调用异步的方法不能写在一个类里,否则会报循环依赖异常,建议另建一个类,只用来放异步方法。