调用方法
@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事物:当方法没有事物时(特殊标记)就加入到调用方法的事物中去