原文链接
业务需求上经常会有一些边缘操作,比如主流程操作A:用户报名课程操作入库,边缘操作B:发送邮件或短信通知。
如何在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注解,可以整个app使用该线程池,而且只要一个@Async注解在方法上面即可,省去重复的submit操作。关于async要注意的几点:
package="com.yami" />
"myExecutor" pool-size="5"/>
"myExecutor" />
这个必须配置在root context里头,而且web context不能扫描controller层外的注解,否则会覆盖掉。
package="com.yami.web.controller"/>
async方法的调用,不能由同类方法内部调用,否则拦截不生效,这是spring默认的拦截问题,必须在其他类里头调用另一个类中带有async的注解方法,才能起到异步效果。
async方法如果也开始事务的话,要注意事务传播以及事务开销的问题。而且在async方法里头使用如上的TransactionSynchronizationManager.registerSynchronization不起作用,值得注意。