所谓异步任务,其实就是异步执行程序,有些时候遇到一些耗时的的任务,如果一直卡等待,肯定会影响其他程序的执行,所以就让这些程序需要以异步的方式去执行。那么下面就来介绍Spring Boot 如何实现异步任务。
Spring中用@Async注解标记的方法,称为异步方法。在spring boot应用中使用@Async很简单:
- 调用异步方法类上或者启动类加上注解@EnableAsync
- 在需要被异步调用的方法外加上@Async
- 所使用的@Async注解方法的类对象应该是Spring容器管理的bean对象
注解配置开启
在springboot启动类(或是配置类)上添加 @EnableAsync 注解
@EnableAsync
public class SpringBootApplication {
}
基于@Async无返回值调用
/**
* 没有返回值的Async方法
*/
@Async
public void asyncMethodWithVoidReturnType() {
log.info("没有返回值的Async方法, ThreadName : {}", Thread.currentThread().getName());
}
基于@Async返回值的调用
/**
* 有返回值的Async方法
* @return Future new AsyncResult
*/
@Override
@Async
public Future<String> asyncMethodWithReturnType() {
log.info("有返回值的Async方法, ThreadName : {}", Thread.currentThread().getName());
try {
Thread.sleep(5000);
return new AsyncResult<String>("hello world !!!!");
} catch (InterruptedException e) {
log.error("出问题了, {}", e.getMessage());
}
return null;
}
以上示例可以发现,返回的数据类型为Future类型,其为一个接口。具体的结果类型为 AsyncResult,这个是需要注意的地方。
调用返回结果的异步方法示例:
@GetMapping("/future")
public String futureAsync() throws ExecutionException, InterruptedException {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("Invoking an asynchronous method. threadName : " + Thread.currentThread().getName());
Future<String> stringFuture = asyncService.asyncMethodWithReturnType();
while (true) {
if (stringFuture.isDone()) {
stringBuilder.append("Result from asynchronous process - " + stringFuture.get());
break;
}
stringBuilder.append("Continue doing something else.");
Thread.sleep(1000);
}
return stringBuilder.toString();
}
分析: 这些获取异步方法的结果信息,是通过不停的检查Future的状态来获取当前的异步方法是否执行完毕来实现的。