Transactor函数式编程启动事务

Transactor函数式编程启动事务

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.function.Supplier;

/**
 * @author: GeorgeWzz
 * @created: 2020/3/20.
 * @updater:
 * @description:事务处理工具
 */
@Component("myTransactor")
public class Transactor {

    private final static Logger LOGGER = LoggerFactory.getLogger(Transactor.class);

    private static Transactor instance;

    public static Transactor getInstance() {
        if (instance == null) {
            try {
                instance = (Transactor) SpringContextHolder.getBean("myTransactor");
            } catch (Exception e) {
                LOGGER.error("获取Transactor对象异常:", e);
            }
        }
        return instance;
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = java.lang.Exception.class)
    public <R> R getThrowsException(SupplierThrowException<R> f) throws Exception {
        return f.get(); // 有返回值的代码块
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = java.lang.Exception.class)
    public <R> R get(Supplier<R> f) {
        return f.get(); // 有返回值的代码块
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = java.lang.Exception.class)
    public <R> R getRequiredNewThrowsException(SupplierThrowException<R> f) throws Exception {
        return f.get(); // 有返回值的代码块
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = java.lang.Exception.class)
    public <R> R getRequiredNew(Supplier<R> f) {
        return f.get(); // 有返回值的代码块
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = java.lang.Exception.class)
    public void run(Runnable f) {
        f.run(); // 无返回值的代码块
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = java.lang.Exception.class)
    public void runThrowsException(RunnableThrowException f) throws Exception {
        f.run(); // 无返回值的代码块
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = java.lang.Exception.class)
    public void runRequiredNew(Runnable f) {
        f.run(); // 无返回值的代码块
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = java.lang.Exception.class)
    public void runRequiredNewThrowsException(RunnableThrowException f) throws Exception {
        f.run(); // 无返回值的代码块
    }


}
/**
 * @author: GeorgeWzz
 * @created: 2019/6/6.
 * @updater:
 * @description:
 */
@FunctionalInterface
public interface RunnableThrowException {
    /**
     * 显示声明抛异常,用于回滚事务
     *
     * @return
     * @throws Exception
     */
    void run() throws Exception;

}
发布了1 篇原创文章 · 获赞 0 · 访问量 4
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 游动-白 设计师: 上身试试

分享到微信朋友圈

×

扫一扫,手机浏览