java事务的传播属性,spring事务传播属性

spring事务传播属性定义在org.springframework.transaction.TransactionDefinition接口,类似于EJB CMT的事务传播属性定义,主要有以下几种类型:

propagation

说明

PROPAGATION_REQUIRED

支持当前事务,如果当前没有事务,则新建一个事务执行

PROPAGATION_SUPPORTS

支持当前事务,如果没有当前事务,则以非事务的方式执行

PROPAGATION_MANDATORY

支持当前事务,如果当前没有事务,则抛出异常

PROPAGATION_REQUIRES_NEW

创建一个新的事务,如果当前已经有事务了,则将当前事务挂起

PROPAGATION_NOT_SUPPORTED

不支持当前事务,而且总是以非事务方式执行

PROPAGATION_NEVER

不支持当前事务,如果存在事务,则抛出异常

PROPAGATION_NESTED

如果当前事务存在,则在嵌套事务中执行,否则行为类似于PROPAGATION_REQUIRED。 EJB中没有类似的功能。

下面,用一个例子来解释下各个传播属性的不同:

在数据库中新建了一张产品表,两条数据,一条产品id为1,产品名称为IPhone6S,另一条产品id为2,产品名称为MAC PRO。

PROPAGATION_REQUIRED

两个服务serviceA和serviceB,serviceA的methodA方法先减IPhone6S的库存,然后调用serviceB中methodB方法扣减MAC Pro库存,为了观察,methodA最后手动抛出异常,模拟回滚场景。

支持当前事务

在传播属性为PROPAGATION_REQUIRED时,事务加入方会使用当前事务,methodA代码为:

public void methodA() {

TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);

try {

transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);

transactionTemplate.execute(status -> {

OrdProduct product = ordProductMapper.selectForUpdate(1);

System.out.println("before update " + product.getProductName() + ", inventory is: " + product.getInventory());

product.setInventory(product.getInventory() - 1);

int result = ordProductMapper.updateInventoryByProductId(1, product.getInventory());

serviceB.methodB();

if (result == 1) {

throw new RuntimeException("test");

}

return result;

});

} finally {

OrdProduct product1 = ordProductMapper.selectForUpdate(1);

OrdProduct product2 = ordProductMapper.selectForUpdate(2);

System.out.println("after update " + product1.getProductName() + ", inventory is: " + product1.getInventory());

System.out.println("after update " + product2.getProductName() + ", inventory is: " + product2.getInventory());

}

}

methodB的代码为:

public void methodB(){

TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);

transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);

transactionTemplate.execute(transactionStatus -> {

OrdProduct product = ordProductMapper.selectForUpdate(2);

System.out.println("before update " + product.getProductName() + ", inventory is: " + product.getInventory());

product.setInventory(product.getInventory() -1 );

int result = ordProductMapper.updateInventoryByProductId(2, product.getInventory());

/*if (result == 1) {

throw new RuntimeException("test");

}*/

return result;

});

}

methodA在完成6s的减库存操作后,调用methodB,methodB的传播属性是PROPAGATION_REQUIRED,此时methodA已经起了事务,methodB会使用现存的事务,在methodA抛出异常后,两个方法的减库存操作都会回滚。

当前没有事务,则新建一个事务

methodA代码逻辑不用transactionTemplate.execute()方式执行,methodB方法去除注释抛出异常,methodB会新建一个事务,执行后methodB会回滚,methodA不会,即mac库存不变,6s库存减1;

PROPAGATION_SUPPORTS

支持当前事务

和PROPAGATION_REQUIRED行为相同;

没有当前事务,则以非事务的方式执行

methodB的传播属性设置为PROPAGATION_SUPPORTS

transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS);

methodA代码逻辑不用transactionTemplate.execute()方式执行,methodB方法去除注释抛出异常,methodB不会新建事务,执行后两个方法都不会回滚,两个产品的库存均减1.

PROPAGATION_MANDATORY

支持当前事务

和PROPAGATION_REQUIRED行为相同;

当前没有事务,则抛出异常

methodB的传播属性设置为PROPAGATION_MANDATORY

transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_MANDATORY);

methodA代码逻辑不用transactionTemplate.execute()方式执行,执行时则会抛出如下异常

org.springframework.transaction.IllegalTransactionStateException: No existing transaction found for transaction marked with propagation 'mandatory'

PROPAGATION_REQUIRES_NEW

在当前没有事务的情况下,行为和PROPAGATION_REQUIRED一致,如果当前已有事务,则将当前事务挂起,开启一个新的事务。

e1848e2aa7c3

tx_prop_requires_new.png

从上图可以看出传播属性是PROPAGATION_REQUIRES_NEW时候的事务执行过程。PROPAGATION_REQUIRES_NEW始终对每个受影响的事务范围采用独立的物理事务,而不受外围事务的影响。

在这样的安排中,底层资源事务是不同的,因此可以独立地提交或回滚,外部事务不受内部事务的回滚状态的影响,并且内部事务的锁在完成后立即释放。这样一个独立的内部事务也可以声明它自己的隔离级别,超时和只读设置,而不是继承外部事务的特性。

独立的物理事务

要理解这一点可以用下面的例子来说明:

public void methodA() {

TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);

try {

transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);

transactionTemplate.execute(status -> {

OrdProduct product = ordProductMapper.selectForUpdate(1);

System.out.println("before update " + product.getProductName() + ", inventory is: " + product.getInventory());

product.setInventory(product.getInventory() - 1);

int result = ordProductMapper.updateInventoryByProductId(1, product.getInventory());

serviceB.methodB();

if (result == 1) {

throw new RuntimeException("test");

}

return result;

});

} finally {

OrdProduct product1 = ordProductMapper.selectForUpdate(1);

OrdProduct product2 = ordProductMapper.selectForUpdate(2);

System.out.println("after update " + product1.getProductName() + ", inventory is: " + product1.getInventory());

System.out.println("after update " + product2.getProductName() + ", inventory is: " + product2.getInventory());

}

}

public void methodB(){

TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);

transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);

transactionTemplate.execute(transactionStatus -> {

OrdProduct product = ordProductMapper.selectForUpdate(2);

System.out.println("before update " + product.getProductName() + ", inventory is: " + product.getInventory());

product.setInventory(product.getInventory() -1 );

int result = ordProductMapper.updateInventoryByProductId(2, product.getInventory());

/*if (result == 1) {

throw new RuntimeException("test");

}*/

return result;

});

}

serviceA抛出异常,serviceB是内部事务,在serviceB的传播行为是PROPAGATION_REQUIRES_NEW时,那么serviceB将开启一个独立的物理事务,并不受外部事务的影响,因此不会回滚,结果可以看到,serviceA中IPhone6S库存不变,serviceB中MAC Pro库存减1.

before update IPhone6S, inventory is: 9985

before update MAC Pro, inventory is: 9989

after update IPhone6S, inventory is: 9985

after update MAC Pro, inventory is: 9988

同样,内部事务的回滚状态也不会影响外部事务,可以用以下的例子来说明:

public void methodA() {

TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);

try {

transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);

transactionTemplate.execute(status -> {

OrdProduct product = ordProductMapper.selectForUpdate(1);

System.out.println("before update " + product.getProductName() + ", inventory is: " + product.getInventory());

product.setInventory(product.getInventory() - 1);

int result = ordProductMapper.updateInventoryByProductId(1, product.getInventory());

serviceB.methodB();

/* if (result == 1) {

throw new RuntimeException("test");

}*/

return result;

});

} finally {

OrdProduct product1 = ordProductMapper.selectForUpdate(1);

OrdProduct product2 = ordProductMapper.selectForUpdate(2);

System.out.println("after update " + product1.getProductName() + ", inventory is: " + product1.getInventory());

System.out.println("after update " + product2.getProductName() + ", inventory is: " + product2.getInventory());

}

}

public void methodB(){

TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);

transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);

transactionTemplate.execute(transactionStatus -> {

OrdProduct product = ordProductMapper.selectForUpdate(2);

System.out.println("before update " + product.getProductName() + ", inventory is: " + product.getInventory());

product.setInventory(product.getInventory() -1 );

int result = ordProductMapper.updateInventoryByProductId(2, product.getInventory());

/*if (result == 1) {

throw new RuntimeException("test");

}*/

transactionStatus.setRollbackOnly();

return result;

});

}

methodA不抛出异常,methodB设置rollbackOnly,结果是methodB回滚,methodA不受影响,不回滚。

before update IPhone6S, inventory is: 9985

before update MAC Pro, inventory is: 9988

after update IPhone6S, inventory is: 9984

after update MAC Pro, inventory is: 9988

而在methodB的传播属性是PROPAGATION_REQUIRED是,methodA会抛出UnexpectedRollbackException,并进行回滚。

PROPAGATION_NOT_SUPPORTED & PROPAGATION_NEVER

这两者都比较好理解,此处不做过多赘述。

PROPAGATION_NESTED

PROPAGATION_NESTED 开始一个 "嵌套的" 事务, 它是已经存在事务的一个真正的子事务. 嵌套事务开始执行时, 它将取得一个 savepoint. 如果这个嵌套事务失败, 我们将回滚到此 savepoint. 嵌套事务是外部事务的一部分, 只有外部事务结束后它才会被提交. 如果外部事务 commit, 嵌套事务也会被 commit, 这个规则同样适用于 roll back.

关于PROPAGATION_NESTED和PROPAGATION_REQUIRES_NEW的区别,spring的创始人之一Juergen Hoeller有以下解释:

PROPAGATION_REQUIRES_NEW starts a new, independent "inner" transaction for the given scope. This transaction will be committed or rolled back completely independent from the outer transaction, having its own isolation scope, its own set of locks, etc. The outer transaction will get suspended at the beginning of the inner one, and resumed once the inner one has completed.

Such independent inner transactions are for example used for id generation through manual sequences, where the access to the sequence table should happen in its own transactions, to keep the lock there as short as possible. The goal there is to avoid tying the sequence locks to the (potentially much longer running) outer transaction, with the sequence lock not getting released before completion of the outer transaction.

PROPAGATION_NESTED on the other hand starts a "nested" transaction, which is a true subtransaction of the existing one. What will happen is that a savepoint will be taken at the start of the nested transaction. if the nested transaction fails, we will roll back to that savepoint. The nested transaction is part of of the outer transaction, so it will only be committed at the end of of the outer transaction.

Nested transactions essentially allow to try some execution subpaths as subtransactions: rolling back to the state at the beginning of the failed subpath, continuing with another subpath or with the main execution path there - all within one isolated transaction, and not losing any previous work done within the outer transaction.

For example, consider parsing a very large input file consisting of account transfer blocks: The entire file should essentially be parsed within one transaction, with one single commit at the end. But if a block fails, its transfers need to be rolled back, writing a failure marker somewhere. You could either start over the entire transaction every time a block fails, remembering which blocks to skip - or you mark each block as a nested transaction, only rolling back that specific set of operations, keeping the previous work of the outer transaction. The latter is of course much more efficient, in particular when a block at the end of the file fails.

需要注意的是,PROPAGATION_NESTED使用JDBC保存点,因此,它只适用于JDBC资源事务。

笔者在实际中也未使用过PROPAGATION_NESTED属性,因此,如果有读者使用碰到问题,欢迎来信一起探讨wgy@live.cn。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值