package com.ruoyi.common.utils;

import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationAdapter;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author : fangk
 * @date : 2024/6/26 16:40
 * @desc : TODO
 */
public class AsyncUtils {

    private final static ExecutorService executor = Executors.newSingleThreadExecutor();


    public static void executeAsyncAfterCommit(Runnable runnable) {
        // 判断当前是否存在事务
        if (!TransactionSynchronizationManager.isSynchronizationActive()) {
            // 无事务，直接提交异步任务

            executor.submit(() -> {
                try {
                    runnable.run();
                } catch (Exception e) {
                    // 记录异常信息，发邮件或者进入待处理列表
                }
            });
            return;
        }

        // 有事务，则添加一个事务同步器，并重写afterCompletion方法（此方法在事务提交后会做回调）
        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {

            @Override
            public void afterCompletion(int status) {
                if (status == TransactionSynchronization.STATUS_COMMITTED) {
                    // 事务提交后，再异步提交任务
                    executor.submit(() -> {
                        try {
                            runnable.run();
                        } catch (Exception e) {
                            // 记录异常信息
                        }
                    });
                }
            }

        });

    }
}
