事務執行器實現

直接上代碼:

// 定義執行接口
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;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章