开发者

dynamically register transaction listener with spring?

I have a springframework application in which I would like to add a transaction listener to a transaction which is currently in progress. The motivation is to trigger a post commit action which notifies downstream systems. I am usi开发者_JAVA技巧ng @Transactional to wrap a transaction around some service method -- which is where I want to create/register the post transaction listener. I want to do something "like" the following.

public class MyService {
 @Transaction
 public void doIt() {
  modifyObjects();

  // something like this
  getTransactionManager().registerPostCommitAction(new 
   TransactionSynchronizationAdapter() {
     public void afterCommit() { 
      notifyDownstream(); 
     }
  });
 }
}

Spring has a TransactionSynchronization interface and adapter class which seems exactly what I want; however it is not immediately clear how to register one dynamically with either the current transaction, or the transaction manager. I would rather not subclass JtaTransactionManager if I can avoid it.

Q: Has anyone done this before.

Q: what is the simplest way to register my adapter?


Actually it was not as hard as I thought; spring has a static helper class that puts the 'right' stuff into the thread context.

TransactionSynchronizationManager.registerSynchronization(
    new TransactionSynchronizationAdapter() {
        @Override
        public void afterCommit() {
            s_logger.info("TRANSACTION COMPLETE!!!");
        }
    }
);


you could use an aspect to match transactional methods aspect in your service to accomplish this:

@Aspect
public class AfterReturningExample {

  @AfterReturning("execution(* com.mypackage.MyService.*(..))")
  public void afterReturning() {
    // ...
  }

}


Here is a more complete solution I did for a similar problem that with wanting my messages sent after transactions are committed (I could have used RabbitMQ TX but they are rather slow).

public class MessageBusUtils {
    public static Optional<MessageBusResourceHolder> getTransactionalResourceHolder(TxMessageBus messageBus) {

        if ( ! TransactionSynchronizationManager.isActualTransactionActive()) {
            return Optional.absent();
        }

        MessageBusResourceHolder o = (MessageBusResourceHolder) TransactionSynchronizationManager.getResource(messageBus);
        if (o != null) return Optional.of(o);

        o = new MessageBusResourceHolder();
        TransactionSynchronizationManager.bindResource(messageBus, o);
        o.setSynchronizedWithTransaction(true);
        if (TransactionSynchronizationManager.isSynchronizationActive()) {
            TransactionSynchronizationManager.registerSynchronization(new MessageBusResourceSynchronization(o, messageBus));
        }
        return Optional.of(o);

    }

    private static class MessageBusResourceSynchronization extends ResourceHolderSynchronization<MessageBusResourceHolder, TxMessageBus> {
        private final TxMessageBus messageBus;
        private final MessageBusResourceHolder holder;

        public MessageBusResourceSynchronization(MessageBusResourceHolder resourceHolder, TxMessageBus resourceKey) {
            super(resourceHolder, resourceKey);
            this.messageBus = resourceKey;
            this.holder = resourceHolder;
        }


        @Override
        protected void cleanupResource(MessageBusResourceHolder resourceHolder, TxMessageBus resourceKey,
                boolean committed) {
            resourceHolder.getPendingMessages().clear();
        }

        @Override
        public void afterCompletion(int status) {
            if (status == TransactionSynchronization.STATUS_COMMITTED) {
                for (Object o : holder.getPendingMessages()) {
                    messageBus.post(o, false);
                }
            }
            else {
                holder.getPendingMessages().clear();
            }
            super.afterCompletion(status);
        }


    }
}

public class MessageBusResourceHolder extends ResourceHolderSupport {

    private List<Object> pendingMessages = Lists.newArrayList();

    public void addMessage(Object message) {
        pendingMessages.add(message);
    }


    protected List<Object> getPendingMessages() {
        return pendingMessages;
    }

}

Now in your class where you actually send the message you will do

@Override
public void postAfterCommit(Object o) {
    Optional<MessageBusResourceHolder> holder = MessageBusTxUtils.getTransactionalResourceHolder(this);
    if (holder.isPresent()) {
        holder.get().addMessage(o);
    }
    else {
        post(o, false);
    }
}

Sorry for the long winded coding samples but hopefully that will show someone how to do something after a commit.


Does it make sense to override the transaction manager on the commit and rollback methods, calling super.commit() right at the beginning.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜