java spring 事务流程控制包装 transactionscope

java spring 中 @transactional 导致整个方法都是事务,无法提前 commit,为了缓存同步,需要在 commit 后清空缓存,就办不到了。

因 c# transactionscope 很方便,于是封装了一个线程安全的 java 版的 transactionscope

import lombok.var;
import net.firstelite.stgl.model.entity.stgl.Society;
import net.firstelite.stgl.web.controller.stgl.WebController;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;

import java.util.List;
import java.util.concurrent.locks.ReentrantLock;

public class TransactionScope implements AutoCloseable {

    private PlatformTransactionManager platformTransactionManager = null;
    private TransactionStatus transaction = null;
    private ReentrantLock handleLock = new ReentrantLock();
    private boolean handled = false;

    public TransactionScope(PlatformTransactionManager platformTransactionManager, TransactionDefinition transactionDefinition) {
        this.platformTransactionManager = platformTransactionManager;
        this.transaction = platformTransactionManager.getTransaction(transactionDefinition);
    }

    public void rollback() {
        try {
            handleLock.lock();
            if (!handled) {
                platformTransactionManager.rollback(transaction);
                handled = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            handleLock.unlock();
        }
    }

    public void commit() {
        try {
            handleLock.lock();
            if (!handled) {
                platformTransactionManager.commit(transaction);
                handled = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            handleLock.unlock();
        }
    }

    @Override
    public void close() {
        this.rollback();
    }
}

实例化事务类:

@Autowired
    private PlatformTransactionManager platformTransactionManager;

    @Autowired
    private TransactionDefinition transactionDefinition;

使用方法:

try(var ts = new TransactionScope(platformTransactionManager,transactionDefinition);)
        {
            //code here
            ts.commit();
        }

这样,你提前 return 不需要做任何操作,代码离开try范围,只要没有执行到 commit 语句,事务就会自动回滚

posted on 2022-07-05 18:16  空明流光  阅读(161)  评论(0编辑  收藏  举报

导航