这篇文章简单介绍下spring的@Async
注解和对应的使用,主要是以springboot来举例。首先这个注解提供了一种方便使用异步编程的功能,仅仅在需要的方法上添加这个注解,就可以让对应的方法异步的执行。实质上,该方法还是放在一个线程池里运行的。我们来看代码例子:
首先是Springboot下的配置,包括生成一个线程池,常用的有核心线程数,最大线程数,阻塞队列等的设置,有个这个线程池,就可以给需要的方法加异步注解了,代码如下。
@Configuration
@EnableAsync
public class SpringAsyncConfiguration implements AsyncConfigurer {
private static final int CORE_POOL_SIZE = 10;
private static final int MAX_POOL_SIZE = 30;
private static final int QUEUE_SIZE = 100;
@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(CORE_POOL_SIZE);
executor.setMaxPoolSize(MAX_POOL_SIZE);
executor.setQueueCapacity(QUEUE_SIZE);
executor.setThreadNamePrefix("AsyncRecordExecutor-");
executor.initialize();
return executor;
}
}
这是个最简单的基本例子,其他复杂情况可以设置异常处理,线程工厂等。注意@EnableAsync如果打开源码,会有对应功能的例子和介绍,非常详细和有用,可以参考。
@Configuration是springboot的配置加载注解,将当前的线程池载入为bean的形式。
下面是几个调用例子:
@Slf4j
@Service
public class DemoService {
@Async
public void printHello() {
while (true) {
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
log.info("print hello " + LocalDateTime.now());
}
}
}
将这个方法调用很多遍,可以看到printHello方法是异步在线程池执行的,至此,我们的功能要求是达到的。对于springMVC的形式,是通过在SpringContext.xml配置文件设置的,在@EnableAsync源码样例中也有介绍,网上资料也比较多,不再赘述。
网友评论