关于java:Spring中的Transactional注解

前言

在上周的开发中,遇到了事务相干的问题,测试环境失常但部署到正式环境就抛出异样,又间断加班几天解决了此问题,现对该问题作出复盘并回顾之前的知识点。如有谬误,欢送斧正。

什么是事务

数据库的事务是一种机制、一个操作序列,蕴含了数据库操作命令。事务把所有的命令做为一个整体一起向零碎提交或撤销操作申请,即这一组命令要么胜利,要么失败。

事务的4个个性(ACID):

  1. 原子性

事务是一个残缺的操作。事务内的各元素是不可分割的。事务中的元素必须作为一个整体提交或回滚。如果事务中的任何元素失败,整个事务将失败。

  1. 一致性

在事务开始前,数据必须处于统一状态;在事务完结后,数据的状态也必须保持一致。通过事务对数据所做的批改不能损坏数据。

  1. 隔离性

事务的执行不受其余事务的烦扰,事务执行的两头后果对其余事务必须是通明的。

  1. 持久性

对于提交的事务,零碎必须保障事务对数据库的扭转不被失落,即便数据库产生故障。

如何实现事务

在目前的业务开发过程中,都是以Spring框架为主。Spring反对两种形式的事务管理编程式事务申明式事务

编程式事务

所谓编程式事务就是手动在代码中实现事务的提交,产生异样时的回滚。

在实现类中注入PlatformTransactionManager

    @Autowired
    private PlatformTransactionManager transactionManager;

    @Override
    public Map<String, Object> saveResource(MultipartFile file) {

        TransactionStatus status = transactionManager.getTransaction(new DefaultTransactionDefinition());
        try {
            // 相干业务
            
            // 手动提交
            transactionManager.commit(status);
        } catch (Exception e) {
            log.error("Exception:{}", ExceptionUtil.stacktraceToString(e));
            // 产生异样时进行回滚
            transactionManager.rollback(status);
        }
    }

申明式事务

所谓申明式事务,就是应用@Transactional注解开启事务,该注解能够放在类上和办法上,放在类上时,该类所有的public办法都会开启事务;放在办法上时,示意以后办法反对事务

    @Transactional
    @Override
    public Map<String, Object> saveResource(MultipartFile file) {
            // 相干业务
    }

@Transactional注解

标有该注解的办法通过AOP实现事务的回滚与提交

先在DispatcherServlet中找到对于的Controller,再通过CgLib增加拦截器,在类ReflectiveMethodInvocation中,有多种拦截器的实现,例如:参数验证,AOP前置拦挡,后置拦挡,抛出异样拦挡,盘绕拦挡等,还有一个是TransactionInterceptor 事务拦截器

调用invoke()办法

事务的大抵执行逻辑

protected Object invokeWithinTransaction(Method method, @Nullable Class<?> targetClass,final InvocationCallback invocation) throws Throwable {
        ...
        PlatformTransactionManager ptm = asPlatformTransactionManager(tm);
        // 切点
        final String joinpointIdentification = methodIdentification(method, targetClass, txAttr);

        if (txAttr == null || !(ptm instanceof CallbackPreferringPlatformTransactionManager)) {
            // Standard transaction demarcation with getTransaction and commit/rollback calls.
            // 创立事务
            TransactionInfo txInfo = createTransactionIfNecessary(ptm, txAttr, joinpointIdentification);

            // 盘绕切点执行业务逻辑
            Object retVal;
            try {
                // This is an around advice: Invoke the next interceptor in the chain.
                // This will normally result in a target object being invoked.
                retVal = invocation.proceedWithInvocation();
            }
            catch (Throwable ex) {
                // target invocation exception
                // 执行过程中产生异样,执行回滚
                completeTransactionAfterThrowing(txInfo, ex);
                throw ex;
            }
            finally {
                cleanupTransactionInfo(txInfo);
            }

            if (vavrPresent && VavrDelegate.isVavrTry(retVal)) {
                // Set rollback-only in case of Vavr failure matching our rollback rules...
                TransactionStatus status = txInfo.getTransactionStatus();
                if (status != null && txAttr != null) {
                    retVal = VavrDelegate.evaluateTryFailure(retVal, txAttr, status);
                }
            }
            // 失常执行,提交事务
            commitTransactionAfterReturning(txInfo);
            return retVal;
        }
        ...
}

completeTransactionAfterThrowing()办法

    protected void completeTransactionAfterThrowing(@Nullable TransactionInfo txInfo, Throwable ex) {
        // 判断事务状态不为空的状况下
        if (txInfo != null && txInfo.getTransactionStatus() != null) {
        // 输入debug日志
            if (logger.isTraceEnabled()) {
                logger.trace("Completing transaction for [" + txInfo.getJoinpointIdentification() +
                        "] after exception: " + ex);
            }
            // 在指定异样下回滚
            if (txInfo.transactionAttribute != null && txInfo.transactionAttribute.rollbackOn(ex)) {
                try {
                    // 开始回滚
                    txInfo.getTransactionManager().rollback(txInfo.getTransactionStatus());
                }
                catch (TransactionSystemException ex2) {
                    logger.error("Application exception overridden by rollback exception", ex);
                    ex2.initApplicationException(ex);
                    throw ex2;
                }
                catch (RuntimeException | Error ex2) {
                    logger.error("Application exception overridden by rollback exception", ex);
                    throw ex2;
                }
            }
            // 不是指定的异样,任然提交
            else {
                // We don't roll back on this exception.
                // Will still roll back if TransactionStatus.isRollbackOnly() is true.
                try {
                    txInfo.getTransactionManager().commit(txInfo.getTransactionStatus());
                }
                catch (TransactionSystemException ex2) {
                    logger.error("Application exception overridden by commit exception", ex);
                    ex2.initApplicationException(ex);
                    throw ex2;
                }
                catch (RuntimeException | Error ex2) {
                    logger.error("Application exception overridden by commit exception", ex);
                    throw ex2;
                }
            }
        }
    }

commitTransactionAfterReturning()办法

// 完结执行,且没有抛出异样,就执行提交
protected void commitTransactionAfterReturning(@Nullable TransactionInfo txInfo) {
        if (txInfo != null && txInfo.getTransactionStatus() != null) {
            if (logger.isTraceEnabled()) {
                logger.trace("Completing transaction for [" + txInfo.getJoinpointIdentification() + "]");
            }
            txInfo.getTransactionManager().commit(txInfo.getTransactionStatus());
        }
    }

罕用属性配置

propagation

配置事务的流传个性,默认为:required

流传性 形容
required 在有事务的状态下执行,如果没有就创立新的事务
required_news 创立新的事务,如果以后有事务就将以后事务挂起
supports 如果有事务就在以后事务下运行,没有事务就在无事务状态下运行
not_supported 在无事务状态下运行,如果有事务,将以后事务挂起
mandatory 必须存在事务,若无事务,抛出异样IllegalTransactionStateException
never 不反对事务,有事务就抛出异样
nested 以后有事务就在当事务外面再起一个事务

isolation

配置事务个隔离级别,默认为以后数据库的默认隔离级别(MySQL为REPEATABLE-READ)

查看数据的隔离级别

隔离性 形容
READ UNCOMMITTED(未提交度) 读取未提交内容,所有事务可看到其余未提交事务的后果,很少理论应用(会呈现脏读)
READ COMMITTED(提交读) 一个事务只能读取到另一个事务已提交事务的批改过的数据,并且其余事务每次对数据进行批改并提交后,该事务都能查问到最新值
REPEATABLE READ(可反复读) 一个是事务读取其实事务曾经提交的批改数据,第一次读取某条记录时,即时其余事务批改了该记录并提交时,之后再读取这条记录时,依然是第一次读取的值,而不是每次读取不同的数据
SERIALIZABLE(串行化) 事务串行化执行,不会呈现踩踏,防止了脏读、幻读和不可反复度,但效率低下

timeout

配置事务超时工夫,默认为:-1

readOnly

当办法外部只须要查问数据时,配置为true

rollbackFor

配置在那些异常情况下须要回滚数据,默认状况下只回滚RuntimeExceptionError,开发中最好配置为Exception

开发过程中遇到的问题

大事务导致事务超时

上周有一个性能,蕴含FTP文件上传及数据库操作,不晓得是不是网络的起因,FTP把文件传输到对方服务器的工夫特地长,导致后续的写库操作无奈执行。前面是通过将性能拆分,不在事务外部执行文件上传,移到外层就行。

事务生效

  1. 非public办法生效

在源码外部对于非public形式执行返回null,不反对对非public的事务反对

  1. rollbackFor配置为默认值

将rollbackFor配置为默认值后,抛出非查看性异样时,事务无奈回滚

  1. 在标有注解的办法汇总在cache中捕捉了异样,没有根底抛出
        Resource resource = new Resource();
        resource.setCreateUser("admin");
        try {
            resourceMapper.insertUseGeneratedKeys(resource);
        } catch (Exception e) {
            // 在日志中输入堆栈信息,并抛出异样
            log.error("Exception:{}", ExceptionUtil.stacktraceToString(e));
            throw new RuntimeException("零碎谬误");
        }
  1. 应用了不反对事务的引擎

在MySQL中反对事务的引擎是innodb

参考文章

  1. JavaGuide (gitee.io)
  2. 一口气说出 6种,@Transactional注解的生效场景 (juejin.cn)
  3. 数据库事务的概念和个性 (biancheng.net)
  4. MySQL :: MySQL 5.7 Reference Manual :: 14.7.2.1 Transaction Isolation Levels

浏览原文

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理