Spring boot
异步任务
# 全局要加上 @EnableAsync
注解
- 定义一个接口
service
一定要加@Async
public interface Service {
@Async
ListenableFuture<String> hello(String name);
}
1
2
3
4
2
3
4
- 实现接口
ServiceImpl
@Component
public class ServiceImpl implements Service {
@Override
public ListenableFuture<String> hello(String name) {
return new AsyncResult("hello" + name);
}
}
1
2
3
4
5
6
7
2
3
4
5
6
7
- 调用
ConfigurableApplicationContext context = SpringApplication.run(DemoApplication.class, args);
Service bean = context.getBean(Service.class);
ListenableFuture<String> hello = bean.hello("li si");
hello.addCallback(System.out::println, System.out::println);
1
2
3
4
2
3
4