业务如图所示:
![](https://i-blog.csdnimg.cn/blog_migrate/d5129a16ff143f1d0d1be25dabeee0c1.png)
子线程serviceB抛出异常,主线程serviceA如何捕获?
Future 有一个方法,future.get();可用 获取任务的结果。但会阻塞队列。
主线程serviceA捕获后,如何回滚?
在serviceA上加上注解Transactional,抛出异常时回滚。
@Transactional(rollbackFor={Exception.class})
代码
主线程serviceA
@Transactional
public void updateTicket(Integer id) {
logger.info("异步 serverB 开始-----------------------");
ticketDao.updateTicket(id);
//模拟业务出现异常
int n = 0 / 0;
logger.info("异步 serverB 结束-----------------------");
}
子线程serviceB
private static final ExecutorService executor = Executors.newSingleThreadExecutor();
@Transactional(rollbackFor={Exception.class})
public User1 update(User1 user1) throws Exception {
//异步执行
Future<String> future = executor.submit(new Callable<String>() {
@Override
public String call() throws Exception {
ticketService.updateTicket(1);
return "ok";
}
});
int update = this.user1Dao.update(user1);
User1 user11 = queryById(user1.getId());
//get()会阻塞队列,获取任务的结果
future.get();
return user11;
}