• 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);
        }
  • 相关阅读:
    11 数据的增删改
    10 外键的变种 三种关系
    09 完整性约束
    03 body标签中的相关标签
    02 body标签中的相关标签
    01 HTML介绍和head标签
    08 数据类型(2)
    07 数据类型
    06 表的操作
    偶遇RecyclerView内部Bug
  • 原文地址:https://www.cnblogs.com/yuyutianxia/p/6961371.html
Copyright © 2020-2023  润新知