直接上代码:
// 定义执行接口
public interface AfterCommitExecutor {
/**
* 执行器
*
* @param runnable
*/
void execute(Runnable runnable);
}
// 接口实现
public class AfterCommitExecutorImpl extends TransactionSynchronizationAdapter implements AfterCommitExecutor {
private static final Logger LOGGER = LoggerFactory.getLogger(AfterCommitExecutorImpl.class);
/**
* 本地线程列表
*/
private static final ThreadLocal<List<Runnable>> RUNNABLE_LIST = new ThreadLocal<>();
/**
* 创建线程池
*/
private static final ExecutorService THREAD_POOL = ThreadPoolFactory.getInstance().defaultPool();
/**
* 事务执行器
*
* @param runnable
*/
@Override
public void execute(Runnable runnable) {
LOGGER.info("Submitting new runnable {} to run after commit", runnable);
if (!TransactionSynchronizationManager.isSynchronizationActive()) {
LOGGER.info("Transaction synchronization is NOT ACTIVE. Executing right now runnable {}", runnable);
runnable.run();
return;
}
List<Runnable> threadRunnableList = RUNNABLE_LIST.get();
if (threadRunnableList == null) {
threadRunnableList = new ArrayList<Runnable>();
RUNNABLE_LIST.set(threadRunnableList);
TransactionSynchronizationManager.registerSynchronization(this);
}
threadRunnableList.add(runnable);
}
/**
* 事务执行完成后触发下步操作
*/
@Override
public void afterCommit() {
List<Runnable> threadRunnables = RUNNABLE_LIST.get();
LOGGER.info("Transaction successfully committed, executing {} runnables", threadRunnables.size());
for (int i = 0; i < threadRunnables.size(); i++) {
Runnable runnable = threadRunnables.get(i);
LOGGER.info("Executing runnable {}", runnable);
try {
THREAD_POOL.execute(runnable);
} catch (RuntimeException e) {
LOGGER.error("Failed to execute runnable " + runnable, e);
}
}
}
/**
* 执行任务完成后移除
*
* @param status
*/
@Override
public void afterCompletion(int status) {
LOGGER.info("Transaction completed with status {}", status == STATUS_COMMITTED ? "COMMITTED" : "ROLLED_BACK");
RUNNABLE_LIST.remove();
}
// 线程池工厂
public class ThreadPoolFactory {
/**
* 单例模式
*/
private ThreadPoolFactory() {
}
/**
* 获取单例
*
* @return
*/
public static ThreadPoolFactory getInstance() {
return ThreadPoolFactorySingle.INSTANCE.getInstance();
}
/**
* 枚举创建单例
*/
private enum ThreadPoolFactorySingle {
INSTANCE;
private ThreadPoolFactory threadPoolFactoryInstance;
ThreadPoolFactorySingle() {
threadPoolFactoryInstance = new ThreadPoolFactory();
}
public ThreadPoolFactory getInstance() {
return threadPoolFactoryInstance;
}
}
/**
* 默认获取系统空闲的线程数
*/
private static final int THREAD_COUNTS = Runtime.getRuntime().availableProcessors();
/**
* 默认线程池名称
*/
private static final String FACTORY_NAME = "DEFAULT_THREAD_POOL";
/**
* 默认队列大小
*/
private static final int QUEUE_SIZE = 3000;
/**
* 默认有界队列
*/
private static final BlockingQueue<Runnable> TASK_QUEUE = new ArrayBlockingQueue<>(QUEUE_SIZE);
/**
* 默认线程池,固定大小,有界队列
*/
private static final ThreadPoolExecutor DEFAULT_THREAD_POOL_EXECUTOR =
new ThreadPoolExecutor(THREAD_COUNTS + 1, THREAD_COUNTS * 2, 60,
TimeUnit.SECONDS, TASK_QUEUE,
new ThreadFactoryBuilder().setNameFormat(FACTORY_NAME).build(),
new ThreadPoolExecutor.DiscardOldestPolicy());
/**
* 自定义线程池
*/
private static ThreadPoolExecutor THREAD_POOL_EXECUTOR = null;
/**
* 创建默认线程池
*
* @return
*/
public ExecutorService defaultPool() {
return DEFAULT_THREAD_POOL_EXECUTOR;
}
/**
* 创建自定义线程池
*
* @return
*/
public ExecutorService create(int coreSize, int maxCoreSize, int queueSize, String poolName) {
// 防止并发
synchronized (this) {
if (THREAD_POOL_EXECUTOR != null) {
return THREAD_POOL_EXECUTOR;
}
// 强行规定有界队列
final BlockingQueue<Runnable> TASK_QUEUE = new ArrayBlockingQueue<>(queueSize);
THREAD_POOL_EXECUTOR = new ThreadPoolExecutor(coreSize, maxCoreSize, 60,
TimeUnit.SECONDS, TASK_QUEUE,
new ThreadFactoryBuilder().setNameFormat(poolName).build(),
new ThreadPoolExecutor.DiscardOldestPolicy());
}
return THREAD_POOL_EXECUTOR;
}
}