springboot事务回滚源码_Springboot事务回滚(改良版)

1 /**

2 * 带回滚的异步任务回调3 * 基类4 *@authorAdministrator5 *6 */

7 public abstract class BaseCallBack implements Callable{8

9 private static Logger logger = LoggerFactory.getLogger(BaseCallBack.class);10 /**

11 * 需要回滚计数器12 */

13 protectedCountDownLatch rollBackLatch;14 /**

15 * 主线程等待计数器16 */

17 protectedCountDownLatch mainThreadLatch;18 /**

19 * 是否需要回滚20 */

21 protectedAtomicBoolean rollbackFlag;22 /**

23 * 事务24 */

25 protectedPlatformTransactionManager transactionManager;26

27 protected abstract voiddoWork();28

29 @Override30 public String call() throwsException {31 if(rollbackFlag.get()) {32 logger.info("需要回滚,直接不用执行了");33 mainThreadLatch.countDown();34 return Constant.ERROR_STR; //如果其他线程已经报错 就停止线程

35 }36 //设置一个事务

37 DefaultTransactionDefinition def = newDefaultTransactionDefinition();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 returnConstant.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 publicCountDownLatch getRollBackLatch() {69 returnrollBackLatch;70 }71

72 public voidsetRollBackLatch(CountDownLatch rollBackLatch) {73 this.rollBackLatch =rollBackLatch;74 }75

76 publicCountDownLatch getMainThreadLatch() {77 returnmainThreadLatch;78 }79

80 public voidsetMainThreadLatch(CountDownLatch mainThreadLatch) {81 this.mainThreadLatch =mainThreadLatch;82 }83

84 publicAtomicBoolean getRollbackFlag() {85 returnrollbackFlag;86 }87

88 public voidsetRollbackFlag(AtomicBoolean rollbackFlag) {89 this.rollbackFlag =rollbackFlag;90 }91

92 publicPlatformTransactionManager getTransactionManager() {93 returntransactionManager;94 }95

96 public voidsetTransactionManager(PlatformTransactionManager transactionManager) {97 this.transactionManager =transactionManager;98 }99

100 }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值