Spring事务Transactional超时时间可能存在的错误认识

本文深入探讨了Spring框架中事务超时的具体实现机制,揭示了事务超时时间的计算方式,并通过实例对比展示了不同代码结构对事务超时判断的影响。强调了在应用设计时考虑远程调用等额外事务时间的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原文:https://jinnianshilongnian.iteye.com/blog/1986023
以下内容是原文截取的结论。不明白的看原文吧。

 

例子:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring-config.xml")
@TransactionConfiguration(transactionManager = "txManager", defaultRollback = false)
@Transactional(timeout = 2)
public class Timeout1Test {
    @Autowired
    private DataSource ds;
    @Test
    public void testTimeout() throws InterruptedException {
        System.out.println(System.currentTimeMillis());
        JdbcTemplate jdbcTemplate = new JdbcTemplate(ds);
        jdbcTemplate.execute(" update test set name = name || '1'");
        System.out.println(System.currentTimeMillis());
        Thread.sleep(3000L);
    }
}

我设置事务超时时间是2秒;但我事务肯定执行3秒以上;为什么没有起作用呢?  这其实是对Spring实现的事务超时的错误认识。那首先分析下Spring事务超时实现吧。

2、分析

           省略,感兴趣的,请移步原文https://jinnianshilongnian.iteye.com/blog/1986023

3、结论

写道

Spring事务超时 = 事务开始时到最后一个Statement创建时时间 + 最后一个Statement的执行时超时时间(即其queryTimeout)。

补充:

本例中,采用的是jdbc事物(org.springframework.jdbc.datasource.DataSourceTransactionManager)
所以,总时长”是从方法开始,到执行完 jdbcTemplate.execute()方法截至。而不是到方法最后!!!!!!

4、因此

假设事务超时时间设置为2秒;假设sql执行时间为1秒;

如下调用是事务不超时的:

  1. public void testTimeout() throws InterruptedException {  
  2.     System.out.println(System.currentTimeMillis());  
  3.     JdbcTemplate jdbcTemplate = new JdbcTemplate(ds);  
  4.     jdbcTemplate.execute(" update test set hobby = hobby || '1'");  
  5.     System.out.println(System.currentTimeMillis());  
  6.     Thread.sleep(3000L);  
  7. }  

而如下事务是超时的:

  1. public void testTimeout() throws InterruptedException {  
  2.     Thread.sleep(3000L);  
  3.     System.out.println(System.currentTimeMillis());  
  4.     JdbcTemplate jdbcTemplate = new JdbcTemplate(ds);  
  5.     jdbcTemplate.execute(" update test set hobby = hobby || '1'");  
  6.     System.out.println(System.currentTimeMillis());  
  7. }  

  

因此,不要忽略应用中如远程调用产生的事务时间和这个事务时间是否对您的事务产生影响。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值