https://www.cnblogs.com/a5513633/p/13969222.html
/**
2 * 带回滚的异步任务回调
3 * 基类
4 * @author Administrator
5 *
6 */
7 public abstract class BaseCallBack implements Callable<String> {
8
9 private static Logger logger = LoggerFactory.getLogger(BaseCallBack.class);
10 /**
11 * 需要回滚计数器
12 */
13 protected CountDownLatch rollBackLatch;
14 /**
15 * 主线程等待计数器
16 */
17 protected CountDownLatch mainThreadLatch;
18 /**
19 * 是否需要回滚
20 */
21 protected AtomicBoolean rollbackFlag;
22 /**
23 * 事务
24 */
25 protected PlatformTransactionManager transactionManager;
26
27 protected abstract void doWork();
28
29 @Override
30 public String call() throws Exception {
31 if (rollbackFlag.get()) {
32 logger.info("需要回滚,直接不用执行了");
33 mainThreadLatch.countDown();
34 return Constant.ERROR_STR; // 如果其他线程已经报错 就停止线程
35 }
36 // 设置一个事务
37 DefaultTransactionDefinition def = new DefaultTransactionDefinition();
38 def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); // 事物隔离级别,开启新事务,这样会比较安全些。
39 TransactionStatus status = transactionManager.getTransaction(def); // 获得事务状态
40 try {
41 logger.info("业务开始处理:{}", this.getClass().getName());
42 this.doWork();
43 logger.info("业务处理结束:{}", this.getClass().getName());
44 // 业务处理结束
45 mainThreadLatch.countDown();
46 logger.info("线程内正常 mainThreadLatch.countDown();");
47 rollBackLatch.await();// 线程等待
48 if (rollbackFlag.get()) {
49 logger.info("回滚事务:{}", this.getClass().getName());
50 transactionManager.rollback(status);
51 } else {
52 logger.info("提交事务:{}", this.getClass().getName());
53 transactionManager.commit(status);
54 }
55 return Constant.SAVE_SUCCESS;
56 } catch (Exception e) {
57 e.printStackTrace();
58 // 如果出错了 就放开锁 让别的线程进入提交/回滚 本线程进行回滚
59 rollbackFlag.set(true);
60 transactionManager.rollback(status);
61 rollBackLatch.countDown();
62 mainThreadLatch.countDown();
63 logger.info("线程内异常 mainThreadLatch.countDown();");
64 return "操作失败:" + e.getMessage();
65 }
66 }
67
68 public CountDownLatch getRollBackLatch() {
69 return rollBackLatch;
70 }
71
72 public void setRollBackLatch(CountDownLatch rollBackLatch) {
73 this.rollBackLatch = rollBackLatch;
74 }
75
76 public CountDownLatch getMainThreadLatch() {
77 return mainThreadLatch;
78 }
79
80 public void setMainThreadLatch(CountDownLatch mainThreadLatch) {
81 this.mainThreadLatch = mainThreadLatch;
82 }
83
84 public AtomicBoolean getRollbackFlag() {
85 return rollbackFlag;
86 }
87
88 public void setRollbackFlag(AtomicBoolean rollbackFlag) {
89 this.rollbackFlag = rollbackFlag;
90 }
91
92 public PlatformTransactionManager getTransactionManager() {
93 return transactionManager;
94 }
95
96 public void setTransactionManager(PlatformTransactionManager transactionManager) {
97 this.transactionManager = transactionManager;
98 }
99
100 }
复制代码