好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Spring事务失效的场景梳理总结

概述

Spring针对Java Transaction API (JTA)、JDBC、Hibernate和Java Persistence API(JPA)等事务 API,实现了一致的编程模型,而Spring的声明式事务功能更是提供了极其方便的事务配置方式,配合Spring Boot的自动配置,大多数Spring Boot项目只需要在方法上标记 @Transactional 注解,即可一键开启方法的事务性配置。

但是,事务如果没有被正确使用,很有可能会导致事务的失效,带来意想不到的数据不一致问题,随后就是大量的人工查找问题和修复数据,本次主要分享Spring事务在技术上的正确使用方式,避免因为事务处理不当导致业务逻辑产生大量偶发性BUG。

事务的传播类型

//如果没有事务就进行创建,存在则加入
@Transactional(propagation=Propagation.REQUIRED)

//不为当前方法开启事务 
@Transactional(propagation=Propagation.NOT_SUPPORTED)

//不管是否存在事务, 都创建一个新的事务, 原来的挂起, 新的执行完毕后, 继续执行老的事务 
@Transactional(propagation=Propagation.REQUIRES_NEW) 

//必须在一个已有的事务中执行, 否则抛出异常
@Transactional(propagation=Propagation.MANDATORY) 

//必须在一个没有的事务中执行, 否则抛出异常(与Propagation.MANDATORY相反)
@Transactional(propagation=Propagation.NEVER) 

//如果其他bean调用这个方法, 在其他bean中声明事务, 那就用事务, 如果其他bean没有声明事务, 那就不用事务
@Transactional(propagation=Propagation.SUPPORTS) 

事务隔离级别

// 读未提交(会出现脏读, 不可重复读) 基本不使用
@Transactional(isolation = Isolation.READ_UNCOMMITTED)

// 读已提交(会出现不可重复读和幻读) Oracle默认
@Transactional(isolation = Isolation.READ_COMMITTED)

// 可重复读(会出现幻读) MySQL默认
@Transactional(isolation = Isolation.REPEATABLE_READ)

// 串行化
@Transactional(isolation = Isolation.SERIALIZABLE)

事务失效的场景

事务方法未被Spring管理

如果事务方法所在的类没有注册到Spring IOC容器中,也就是说,事务方法所在类并没有被Spring管理,则Spring事务会失效,举个例子:

?

1

2

3

4

5

6

7

8

public class BackGroupServiceImpl {

     @Autowired

     private SelfHelpBackgroundMapper backgroundMapper;

     @Transactional (propagation = Propagation.REQUIRES_NEW)

     public void updateSelfHelpBackground(SelfHelpBackground background) {

         backgroundMapper.updateByPrimaryKey(background);

     }

}

BackGroupServiceImpl 实现类上没有添加 @Service注解,实例也就没有被加载到Spring IOC容器,此时updateSelfHelpBackground()方法的事务就会在Spring中失效。

同一个类中的事务方法被非事务方法调用

?

1

2

3

4

5

6

7

8

9

10

11

12

@Service

public class BackGroupServiceImpl {

     @Autowired

     private SelfHelpBackgroundMapper backgroundMapper;

     @Transactional (propagation = Propagation.REQUIRED)

     public   void updateSelfHelpBackground(SelfHelpBackground background) {

         backgroundMapper.updateByPrimaryKey(background);

     }

     public void updateBackground(){

         updateSelfHelpBackground( new SelfHelpBackground());

     }

}

updateBackgroup() 方法和 updateSelfHelpBackgroup() 方法都在BackGroupServiceImpl类中,然而 updateBackgroup() 方法没有添加事务注解, updateSelfHelpBackgroup() 方法虽然添加了事务注解,这种情况 updateSelfHelpBackgroup() 会在Spring事务中失效。

方法的事务传播类型不支持事务

?

1

2

3

4

5

6

7

8

9

10

11

12

13

@Service

public class BackGroupServiceImpl {

     @Autowired

     private SelfHelpBackgroundMapper backgroundMapper;

     @Transactional (propagation = Propagation.REQUIRED)

     public   void updateSelfHelpBackground(SelfHelpBackground background) {

         backgroundMapper.updateByPrimaryKey(background);

     }

     @Transactional (propagation = Propagation.NOT_SUPPORTED)

     public void updateBackground(SelfHelpBackground background){

        backgroundMapper.updateByPrimaryKey(background);

     }

}

如果内部方法的事务传播类型为不支持事务的传播类型,则内部方法的事务同样会在Spring中失效,如@Transactional(propagation = Propagation.NOT_SUPPORTED)

异常被内部catch,程序生吞异常

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

@Service

public class OrderServiceImpl{

     @Autowired

     private OrderMapper orderMapper;

     @Autowired

     private ProductMapper productMapper;

     @Override

     @Transactional (propagation = Propagation.REQUIRES_NEW)

     public ResponseEntity submitOrder(Order order) {

         long orderNo = Math.abs(ThreadLocalRandom.current().nextLong( 1000 ));

         order.setOrderNo( "ORDER_" + orderNo);

         orderMapper.insert(order);

         // 扣减库存

         this .updateProductStockById(order.getProductId(), 1L);

         return new ResponseEntity(HttpStatus.OK);

     }

     /**

      * 事务类型声明为NOT_SUPPORTED不支持事务的传播

      */

     @Transactional (propagation = Propagation.NOT_SUPPORTED)

     public void updateProductStockById(Integer num, Long productId) {

         try {

             productMapper.updateProductStockById(num, productId);

         } catch (Exception e) {

             // 这里仅仅是捕获异常之后的打印(相当于程序吞掉了异常)

             log.error( "Error updating product Stock: {}" , e);

         }

     }

}

数据库不支持事务

Spring事务生效的前提是连接的数据库支持事务,如果底层的数据库都不支持事务,则Spring事务肯定会失效的,例如:使用MySQL数据库,选用 MyISAM 存储引擎,因为 MyISAM 存储引擎本身不支持事务,因此事务毫无疑问会失效

未配置开启事务

如果项目中没有配置Spring的事务管理器,即使使用了Spring的事务管理功能,Spring的事务也不会生效,例如,如果你是Spring Boot项目,没有在SpringBoot项目中配置如下代码:

?

1

2

3

4

@Bean

public PlatformTransactionManager transactionManager(DataSource dataSource) {

     return new DataSourceTransactionManager(dataSource);

}

多线程调用

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

@Slf4j

@Service

public class OrderServiceImpl {

     @Autowired

     private OrderMapper orderMapper;

     @Autowired

     private MessageService messageService;

     @Transactional

     public void orderCommit(orderModel orderModel) throws Exception {

         orderMapper.insertOrder(orderModel);

         new Thread(() -> {

             messageService.sendSms();

         }).start();

     }

}

@Service

public class MessageService {

     @Transactional

     public void sendSms() {

         // 发送短信

     }

}

通过示例,我们可以看到订单提交的事务方法 orderCommit() 中,调用了发送短信的事务方法 sendSms() ,但是发送短信的事务方法 sendSms() 是另起了一个线程调用的。

这样会导致两个方法不在同一个线程中,从而是两个不同的事务。如果是 sendSms() 方法中抛了异常, orderCommit() 方法也回滚是不可能的。

实际上,Spring的事务是通过ThreadLocal来保证线程安全的,事务和当前线程绑定,多个线程自然会让事务失效。

到此这篇关于Spring事务失效的场景梳理总结的文章就介绍到这了,更多相关Spring事务失效场景内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

原文链接:https://blog.csdn.net/xiaosemei/article/details/129146441

查看更多关于Spring事务失效的场景梳理总结的详细内容...

  阅读:11次