Spring @Async
Posted 是谁扭曲了时空
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring @Async相关的知识,希望对你有一定的参考价值。
引入
@SpringBootApplication
@EnableAsync
public class ProjectApplication {
public static void main(String[] args) {
SpringApplication.run(ProjectApplication.class, args);
}
}
使用
@Slf4j
public class TestService {
@Async
@Transactional //事务无效
public void asyncVoid() {
TestService testService = SpringUtil.getBean(TestService.class); //获取代理类proxy
testService.update(); //事务有效
System.out.println("无返回值方法");
}
@Async
@Transactional //事务无效
public Future<String> asynReturn() {
System.out.println("返回值Future(AsyncResult)");
try {
Thread.sleep(3000);
TestService testService = SpringUtil.getBean(TestService.class); //获取代理类proxy
testService.update(); //事务有效
return new AsyncResult<String>("异步返回");
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
@Transactional
public void update(){
System.out.println("操作数据库");
}
public void callAsync() throws InterruptedException, ExecutionException, TimeoutException {
TestService testService = SpringUtil.getBean(TestService.class); //获取代理类proxy
Future<String> future = testService.asynReturn();
String result = future.get(2L, TimeUnit.SECONDS); //等待2秒后获取
}
}
以上是关于Spring @Async的主要内容,如果未能解决你的问题,请参考以下文章