一.异步调用
同步调用就是客户端等待调用执行完成并返回结果。 异步调用就是客户端不等待调用执行完成返回结果,不过依然可以通过回调函数等接收到返回结果的通知。 ... 而异步调用指:程序在执行时,无需等待执行的返回值可继续执行后面的代码。
二.开启异步调用
1.在启动类上添加@EnableAsync注解
@Configuration
@EnableAsync
public class SpringAsyncConfig { ... }
2.基于xml文件配置
Bean文件配置: spring_async.xml
<!-- 等价于 @EnableAsync, executor指定线程池 -->
<task:annotation-driven executor="xmlExecutor"/>
<!-- id指定线程池产生线程名称的前缀 -->
<task:executor
id="xmlExecutor"
pool-size="5-25"
queue-capacity="100"
keep-alive="120"
rejection-policy="CALLER_RUNS"/>
三.@Async用法
1. 最简单的异步调用,返回值为void
2. 带参数的异步调用 异步方法可以传入参数
3. 异常调用返回Future
1.返回值为void,且无参数
@Async //标注使用
public void asyncMethodWithVoidReturnType() {
System.out.println("Execute method asynchronously. "
+ Thread.currentThread().getName());
}
2.同1一样,只不过带有参数
3.如果想查看异步调用的返回内容,可以用这个方法
@Async
public Future<String> asyncInvokeReturnFuture(int i) {
log.info("asyncInvokeReturnFuture, parementer={}", i);
Future<String> future;
try {
Thread.sleep(1000 * 1);
future = new AsyncResult<String>("success:" + i);
} catch (InterruptedException e) {
future = new AsyncResult<String>("error");
}
return future;
}