• spring自定义事务同步器(二):借助redisson实现自己的同步器


    1. 借助redis的java客户端redisson实现自己的事物同步器

        @Override
        public void lockWithinCurrentTransaction(Object key) {
            TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
                @Override
                public void afterCompletion(int status) {
                    unLock(key);
                }
            });
    
            lock(key);
        }
    
        private void lock(Object key) {
    
            RLock rlock = redissonClient.getLock(key.toString());
            if (!rlock.isHeldByCurrentThread()) {
                rlock.lock();
            }
    
        }
    
        private void unLock(Object key) {
    
            RLock rlock = redissonClient.getLock(key.toString());
            if (rlock.isHeldByCurrentThread())
                rlock.unlock();
    
        }

    2.源码分析

        private static final ThreadLocal<Set<TransactionSynchronization>> synchronizations =
                new NamedThreadLocal<Set<TransactionSynchronization>>("Transaction synchronizations");
        /**
         * Register a new transaction synchronization for the current thread.
         * Typically called by resource management code.
         * <p>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");
            if (!isSynchronizationActive()) {
                throw new IllegalStateException("Transaction synchronization is not active");
            }
            synchronizations.get().add(synchronization);
        }
  • 相关阅读:
    python学习之调试:
    python学习之调试 错误捕捉及处理
    python之面向对象
    python学习之模块:
    python学习之内部函数:
    python学习之高级特性:
    python学习之结构语句
    python学习之列表元组,字典
    getopt使用例子
    找到系统盘被打满文件
  • 原文地址:https://www.cnblogs.com/yuyutianxia/p/6961371.html
Copyright © 2020-2023  润新知