• 聊聊spring的TransactionSynchronizationAdapter


    本文主要研究一下spring的TransactionSynchronizationAdapter

    示例代码

    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...");
                }
            }
           );
            System.out.println("service end");
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    使用TransactionSynchronizationManager.registerSynchronization注册了一个TransactionSynchronizationAdapter,在其afterCommit方法也就是事务提交成功之后执行一些额外逻辑

    TransactionSynchronizationAdapter

    org/springframework/transaction/support/TransactionSynchronizationAdapter.java

    public abstract class TransactionSynchronizationAdapter implements TransactionSynchronization, Ordered {
    
    	@Override
    	public int getOrder() {
    		return Ordered.LOWEST_PRECEDENCE;
    	}
    
    	@Override
    	public void suspend() {
    	}
    
    	@Override
    	public void resume() {
    	}
    
    	@Override
    	public void flush() {
    	}
    
    	@Override
    	public void beforeCommit(boolean readOnly) {
    	}
    
    	@Override
    	public void beforeCompletion() {
    	}
    
    	@Override
    	public void afterCommit() {
    	}
    
    	@Override
    	public void afterCompletion(int status) {
    	}
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36

    TransactionSynchronizationAdapter是个抽象类,声明实现TransactionSynchronization及Ordered接口

    TransactionSynchronization

    org/springframework/transaction/support/TransactionSynchronization.java

    	/**
    	 * Invoked after transaction commit. Can perform further operations right
    	 * after the main transaction has successfully committed.
    	 * 

    Can e.g. commit further operations that are supposed to follow on a successful * commit of the main transaction, like confirmation messages or emails. *

    NOTE: The transaction will have been committed already, but the * transactional resources might still be active and accessible. As a consequence, * any data access code triggered at this point will still "participate" in the * original transaction, allowing to perform some cleanup (with no commit following * anymore!), unless it explicitly declares that it needs to run in a separate * transaction. Hence: Use {@code PROPAGATION_REQUIRES_NEW} for any * transactional operation that is called from here. * @throws RuntimeException in case of errors; will be propagated to the caller * (note: do not throw TransactionException subclasses here!) */ default void afterCommit() { }

    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    注意这里注释说明了异常不会被捕获,而且建议不在这里抛出TransactionException的子类;另外对于afterCommit有数据库相关操作的建议使用PROPAGATION_REQUIRES_NEW这个事务传播级别,不然afterCommit的操作可能不会生效

    registerSynchronization

    org/springframework/transaction/support/TransactionSynchronizationManager.java

    
    	private static final ThreadLocal> synchronizations =
    			new NamedThreadLocal<>("Transaction synchronizations");
    
    	/**
    	 * Register a new transaction synchronization for the current thread.
    	 * Typically called by resource management code.
    	 * 

    Note that synchronizations can implement the * {@link org.springframework.core.Ordered} interface. * They will be executed in an order according to their order value (if any). * @param synchronization the synchronization object to register * @throws IllegalStateException if transaction synchronization is not active * @see org.springframework.core.Ordered */ public static void registerSynchronization(TransactionSynchronization synchronization) throws IllegalStateException { Assert.notNull(synchronization, "TransactionSynchronization must not be null"); Set synchs = synchronizations.get(); if (synchs == null) { throw new IllegalStateException("Transaction synchronization is not active"); } synchs.add(synchronization); }

    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    TransactionSynchronizationManager的registerSynchronization方法会把TransactionSynchronization注册到当前线程的synchronizations

    processCommit

    org/springframework/transaction/support/AbstractPlatformTransactionManager.java

    private void processCommit(DefaultTransactionStatus status) throws TransactionException {
    		try {
    			boolean beforeCompletionInvoked = false;
    
    			try {
    				boolean unexpectedRollback = false;
    				prepareForCommit(status);
    				triggerBeforeCommit(status);
    				triggerBeforeCompletion(status);
    				beforeCompletionInvoked = true;
    
    				if (status.hasSavepoint()) {
    					if (status.isDebug()) {
    						logger.debug("Releasing transaction savepoint");
    					}
    					unexpectedRollback = status.isGlobalRollbackOnly();
    					status.releaseHeldSavepoint();
    				}
    				else if (status.isNewTransaction()) {
    					if (status.isDebug()) {
    						logger.debug("Initiating transaction commit");
    					}
    					unexpectedRollback = status.isGlobalRollbackOnly();
    					doCommit(status);
    				}
    				else if (isFailEarlyOnGlobalRollbackOnly()) {
    					unexpectedRollback = status.isGlobalRollbackOnly();
    				}
    
    				// Throw UnexpectedRollbackException if we have a global rollback-only
    				// marker but still didn't get a corresponding exception from commit.
    				if (unexpectedRollback) {
    					throw new UnexpectedRollbackException(
    							"Transaction silently rolled back because it has been marked as rollback-only");
    				}
    			}
    			catch (UnexpectedRollbackException ex) {
    				// can only be caused by doCommit
    				triggerAfterCompletion(status, TransactionSynchronization.STATUS_ROLLED_BACK);
    				throw ex;
    			}
    			catch (TransactionException ex) {
    				// can only be caused by doCommit
    				if (isRollbackOnCommitFailure()) {
    					doRollbackOnCommitException(status, ex);
    				}
    				else {
    					triggerAfterCompletion(status, TransactionSynchronization.STATUS_UNKNOWN);
    				}
    				throw ex;
    			}
    			catch (RuntimeException | Error ex) {
    				if (!beforeCompletionInvoked) {
    					triggerBeforeCompletion(status);
    				}
    				doRollbackOnCommitException(status, ex);
    				throw ex;
    			}
    
    			// Trigger afterCommit callbacks, with an exception thrown there
    			// propagated to callers but the transaction still considered as committed.
    			try {
    				triggerAfterCommit(status);
    			}
    			finally {
    				triggerAfterCompletion(status, TransactionSynchronization.STATUS_COMMITTED);
    			}
    
    		}
    		finally {
    			cleanupAfterCompletion(status);
    		}
    	}
    
    	private void triggerAfterCommit(DefaultTransactionStatus status) {
    		if (status.isNewSynchronization()) {
    			if (status.isDebug()) {
    				logger.trace("Triggering afterCommit synchronization");
    			}
    			TransactionSynchronizationUtils.triggerAfterCommit();
    		}
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82

    AbstractPlatformTransactionManager的processCommit方法,在提交成功之后触发triggerAfterCommit,这里调用了TransactionSynchronizationUtils.triggerAfterCommit(),注意这里没有try catch,说明triggerAfterCommit的异常最终会抛给调用方

    triggerAfterCommit

    org/springframework/transaction/support/TransactionSynchronizationUtils.java

    	public static void triggerAfterCommit() {
    		invokeAfterCommit(TransactionSynchronizationManager.getSynchronizations());
    	}
    
    	public static void invokeAfterCommit(@Nullable List synchronizations) {
    		if (synchronizations != null) {
    			for (TransactionSynchronization synchronization : synchronizations) {
    				synchronization.afterCommit();
    			}
    		}
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    这里遍历synchronizations执行afterCommit方法,如果其中有一个有异常抛出则中断

    小结

    使用TransactionSynchronizationManager.registerSynchronization可以在当前线程的事务注册一个TransactionSynchronizationAdapter,可以在afterCommit方法也就是事务提交成功之后执行一些额外逻辑;注意这里抛出的异常不影响事务提交,但是异常不会被catch需要由调用方处理,对于afterCommit有数据库相关操作的建议使用PROPAGATION_REQUIRES_NEW这个事务传播级别,不然afterCommit的db操作可能不会生效。

    在事务提交之后做一些事情可能不需要TransactionSynchronizationManager.registerSynchronization这种方式也能实现,也就是需要额外一层来调用事务操作,有异常会抛出,没有异常则执行事务提交之后的事情,前提就是事务回滚异常不能被吞掉,不然外层调用可能以为事务成功了
    还有一种方式就是使用TransactionalEventListener,这种方式比TransactionSynchronizationManager.registerSynchronization更为优雅一些

    doc

  • 相关阅读:
    【机器学习——决策树算法——Python实现——信用评级】
    本地安装多个node版本,gvnm来安装切换使用。vue2和vue3对node版本要求不一样
    百度百家号旋转验证码识别研究
    黑客之批处理编写
    Qt添加自定义字体
    编程基础 —— 链表
    计及新能源出力不确定性的电气设备综合能源系统协同优化(Matlab代码实现)
    CentOS 7 使用pugixml 库
    在 Node.js 中操作 Redis
    RabbitMQ队列持久化的重要性与意义
  • 原文地址:https://blog.csdn.net/hello_ejb3/article/details/132781877