spring 事务超时

@Transactional(timeout = 10)

表示设置事务的超时时间为10秒

表示超过10秒如果该事务中所有的DML语句还没有执行完毕的话,最终结果会选择回滚

默认值-1,表示没有时间限制。

如果最后一条DML语句后面还有很多业务逻辑,这些业务代码执行的时间不被计入超时时间

package com.service;

import com.dao.AccountDao;
import com.pojo.Account;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @program: spring_learn
 * @description:
 * @author: Mr.Wang
 * @create: 2023-06-09 07:09
 **/
@Service
public class Service02 {

    @Resource(name="accountDao")
    public AccountDao accountDao;

    @Transactional(timeout = 10)
    public void update(Account act) {
        accountDao.update(act);
        // 睡眠一会
        try {
            Thread.sleep(1000 * 20);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

test:

package com;

import com.pojo.Account;
import com.service.Service01;
import com.service.Service02;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @program: spring_learn
 * @description:
 * @author: Mr.Wang
 * @create: 2023-06-09 07:47
 **/
public class IsolationTest {

    
    @Test
    public void testIsolation2(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
        Service02 i2 = applicationContext.getBean("service02", Service02.class);
        Account act = new Account("004", 1000.0);
        i2.update(act);
    }
}

Before testing 

 

After testing 

// 睡眠一会
try {
    Thread.sleep(1000 * 20);
} catch (InterruptedException e) {
    e.printStackTrace();
}

这里睡眠的 20 秒在最后一条DML语句之后,不计入 timeout 时间之内

交换执行顺序,先休眠20秒,再执行DML语句:

package com.service;

import com.dao.AccountDao;
import com.pojo.Account;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @program: spring_learn
 * @description:
 * @author: Mr.Wang
 * @create: 2023-06-09 07:09
 **/
@Service
public class Service02 {

    @Resource(name="accountDao")
    public AccountDao accountDao;

    @Transactional(timeout = 10)
    public void update(Account act) {
        
        // 睡眠一会
        try {
            Thread.sleep(1000 * 20);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        accountDao.update(act);
    }
}

 Before testing 

 

retest:

 After testing :

数据未更新

 再最后一条DML语句之前,休眠20秒, 会计入 timeout 时间之内,事务超时,回滚

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值