方法中有for update时具体执行过程

调用方法

@RestController
@RequestMapping("/test")
public class TestController {

    @Resource
    private TestServiceImpl testService;

    @GetMapping("/test20/{id}")
    public void test20(@PathVariable Integer id){
        testService.test20(id);
    }

    @GetMapping("/test21/{id}")
    public void test21(@PathVariable Integer id){
        testService.test21(id);
    }

}

调用加锁方法

@Service
@Transactional(rollbackFor = Exception.class)
public class TestServiceImpl extends ServiceImpl<TestMapper, Test> implements TestService {

    @Resource
    private AuthorsService authorsService;

    @Override
    public void test20(Integer id) {
        authorsService.test(id);
        authorsService.test0(id);
    }

    @Override
    public void test21(Integer id) {
        authorsService.test1(id);
    }

}

具体加锁方法

@Service
@Transactional(rollbackFor = Exception.class)
@Slf4j
public class AuthorsServiceImpl extends ServiceImpl<AuthorsMapper, Authors> implements AuthorsService {

    @Override
    @SneakyThrows
    public void test0(Integer id) {
        log.info("--->test0");
        Thread.sleep(5000);
        log.info("--->test0");
    }

    @Override
    @SneakyThrows
    public void test(Integer id) {
        log.info("--->test");
        Authors forUpdate = lambdaQuery().eq(Authors::getId, id).last("for update").one();
        Thread.sleep(10000);
        log.info("--->test");
    }

    @Override
    @SneakyThrows
    public void test1(Integer id) {
        log.info("--->test1");
        Authors forUpdate = lambdaQuery().eq(Authors::getId, id).last("for update").one();
        log.info("--->test1");
    }
}

先执行/test21/{id}方法(调用带for update方法(强制睡眠10秒), 然后再调用一个睡眠5秒种的方法),

随后执行/test20/{id}方法 (调用带for update方法(没有睡眠时间))

结果:

test20方法执行时间: 10 + 5 = 15秒

test21方法执行时间: 14秒

原因:

test20执行 ->调用带for update方法 (锁10秒) -> (调用睡眠5秒种的方法)

test21执行 ->调用带for update方法(没有睡眠时间)-> 由于for update方法被test20方法调用,此时事物还没提交,要等(test20方法)全部执行完后事物再提交,才能释放锁,所以test21方法执行时间也比较长

spring事物:当方法没有事物时(特殊标记)就加入到调用方法的事物中去

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值