public class TransactionSynchronizer { private final static Logger logger = LoggerFactory.getLogger(TransactionSynchronizer.class); public static void afterCommit(final Runnable runnable) { if (TransactionSynchronizationManager.isActualTransactionActive()) { TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() { @Override public void afterCommit() { runnable.run(); } }); } else { //directly call runnable.run(); } } @SuppressWarnings("unchecked") public static <T> Future<T> afterCommit(final Callable<T> callable) { final TransactionFuture<T> future = new TransactionFuture<>(); if (TransactionSynchronizationManager.isActualTransactionActive()) { TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() { @Override public void afterCommit() { try { future.put(callable.call()); } catch (Exception e) { e.printStackTrace(); } } }); } else { //directly call try { future.put(callable.call()); } catch (Exception e) { future.cancel(true); } } return future; } /** * after commit or rollback */ public static void afterCompletion(final Runnable runnable) { if (TransactionSynchronizationManager.isActualTransactionActive()) { TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() { @Override public void afterCompletion(int status) { runnable.run(); } }); } else { //directly call runnable.run(); } } @SuppressWarnings("unchecked") public static <T> Future<T> afterCompletion(final Callable<T> callable) { final TransactionFuture<T> future = new TransactionFuture<>(); if (TransactionSynchronizationManager.isActualTransactionActive()) { TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() { @Override public void afterCompletion(int status) { try { future.put(callable.call()); } catch (Exception e) { logger.error("error calling callable.", e); future.cancel(true); } } }); } else { //directly call try { future.put(callable.call()); } catch (Exception e) { logger.error("error calling callable.", e); future.cancel(true); } } return future; } }
TransactionSynchronizationManager TransactionSynchronizationAdapter
时间: 2024-10-08 20:33:54