引入
@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秒后获取
}
}