mysql 事务两步提交_如何在数据库事务提交成功后进行异步操作

问题

业务场景

业务需求上经常会有一些边缘操作,比如主流程操作A:用户报名课程操作入库,边缘操作B:发送邮件或短信通知。

业务要求

操作A操作数据库失败后,事务回滚,那么操作B不能执行。

操作A执行成功后,操作B也必须执行成功

如何实现

普通的执行A,之后执行B,是可以满足要求1,对于要求2通常需要设计补偿的操作

一般边缘的操作,通常会设置成为异步的,以提升性能,比如发送MQ,业务系统负责事务成功后消息发送成功,然后接收系统负责保证通知成功完成

本文内容

如何在spring事务提交之后进行异步操作,这些异步操作必须得在该事务成功提交后才执行,回滚则不执行。

要点

如何在spring事务提交之后操作

如何把操作异步化

实现方案

使用TransactionSynchronizationManager在事务提交之后操作

public void insert(TechBook techBook){

bookMapper.insert(techBook);

// send after tx commit but is async

TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {

@Override

public void afterCommit() {

System.out.println("send email after transaction commit...");

}

}

);

ThreadLocalRandom random = ThreadLocalRandom.current();

if(random.nextInt() % 2 ==0){

throw new RuntimeException("test email transaction");

}

System.out.println("service end");

}

该方法就可以实现在事务提交之后进行操作

操作异步化

使用mq或线程池来进行异步,比如使用线程池:

private final ExecutorService executorService = Executors.newFixedThreadPool(5);

public void insert(TechBook techBook){

bookMapper.insert(techBook);

// send after tx commit but is async

TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {

@Override

public void afterCommit() {

executorService.submit(new Runnable() {

@Override

public void run() {

System.out.println("send email after transaction commit...");

try {

Thread.sleep(10*1000);

} catch (InterruptedException e) {

e.printStackTrace();

}

System.out.println("complete send email after transaction commit...");

}

});

}

}

);

// async work but tx not work, execute even when tx is rollback

// asyncService.executeAfterTxComplete();

ThreadLocalRandom random = ThreadLocalRandom.current();

if(random.nextInt() % 2 ==0){

throw new RuntimeException("test email transaction");

}

System.out.println("service end");

}

封装以上两步

对于第二步来说,如果这类方法比较多的话,则写起来重复性太多,因而,抽象出来如下:

这里改造了azagorneanu的代码:

public interface AfterCommitExecutor extends Executor {

}

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import org.springframework.stereotype.Component;

import org.springframework.transaction.support.TransactionSynchronizationAdapter;

import org.springframework.transaction.support.TransactionSynchronizationManager;

import java.util.ArrayList;

import java.util.List;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

@Component

public class AfterCommitExecutorImpl extends TransactionSynchronizationAdapter implements AfterCommitExecutor {

private static final Logger LOGGER = LoggerFactory.getLogger(AfterCommitExecutorImpl.class);

private static final ThreadLocal> RUNNABLES = new ThreadLocal>();

private ExecutorService threadPool = Executors.newFixedThreadPool(5);

@Override

public void execute(Runnable runnable) {

LOGGER.info("Submitting new runnable {} to run after commit", runnable);

if (!TransactionSynchronizationManager.isSynchronizationActive()) {

LOGGER.info("Transaction synchronization is NOT ACTIVE. Executing right now runnable {}", runnable);

runnable.run();

return;

}

List threadRunnables = RUNNABLES.get();

if (threadRunnables == null) {

threadRunnables = new ArrayList();

RUNNABLES.set(threadRunnables);

TransactionSynchronizationManager.registerSynchronization(this);

}

threadRunnables.add(runnable);

}

@Override

public void afterCommit() {

List threadRunnables = RUNNABLES.get();

LOGGER.info("Transaction successfully committed, executing {} runnables", threadRunnables.size());

for (int i = 0; i < threadRunnables.size(); i++) {

Runnable runnable = threadRunnables.get(i);

LOGGER.info("Executing runnable {}", runnable);

try {

threadPool.execute(runnable);

} catch (RuntimeException e) {

LOGGER.error("Failed to execute runnable " + runnable, e);

}

}

}

@Override

public void afterCompletion(int status) {

LOGGER.info("Transaction completed with status {}", status == STATUS_COMMITTED ? "COMMITTED" : "ROLLED_BACK");

RUNNABLES.remove();

}

}

public void insert(TechBook techBook){

bookMapper.insert(techBook);

// send after tx commit but is async

// TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {

// @Override

// public void afterCommit() {

// executorService.submit(new Runnable() {

// @Override

// public void run() {

// System.out.println("send email after transaction commit...");

// try {

// Thread.sleep(10*1000);

// } catch (InterruptedException e) {

// e.printStackTrace();

// }

// System.out.println("complete send email after transaction commit...");

// }

// });

// }

// }

// );

//send after tx commit and is async

afterCommitExecutor.execute(new Runnable() {

@Override

public void run() {

try {

Thread.sleep(5*1000);

} catch (InterruptedException e) {

e.printStackTrace();

}

System.out.println("send email after transactioin commit");

}

});

// async work but tx not work, execute even when tx is rollback

// asyncService.executeAfterTxComplete();

ThreadLocalRandom random = ThreadLocalRandom.current();

if(random.nextInt() % 2 ==0){

throw new RuntimeException("test email transaction");

}

System.out.println("service end");

}

关于Spring的Async

spring为了方便应用使用线程池进行异步化,默认提供了@Async注解,可以整个app使用该线程池,而且只要一个@Async注解在方法上面即可,省去重复的submit操作。关于async要注意的几点:

1、async的配置

这个必须配置在root context里头,而且web context不能扫描controller层外的注解,否则会覆盖掉。

2、async的调用问题

async方法的调用,不能由同类方法内部调用,否则拦截不生效,这是spring默认的拦截问题,必须在其他类里头调用另一个类中带有async的注解方法,才能起到异步效果。

3、事务问题

async方法如果也开始事务的话,要注意事务传播以及事务开销的问题。而且在async方法里头使用如上的TransactionSynchronizationManager.registerSynchronization不起作用,值得注意。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值