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);
}
05-11 10:56