Silentdoer

导航

select for update在springboot里实现分布式锁

// mapper,注意,这里的参数最好就是主键或者唯一键,否则产生的是表锁,script可以省略
@Select("<script> select* from foo where id = #{id} for update</script>")
Foo selectForUpdateById(@Param("id") Long id);


// service,必须加事物,否则selectForUpdateById无法实现分布式锁的作用
@Transactional(rollbackFor = Exception.class, propagation = Propatation.REQUIRED)
public void test() {
    log.info("任意进程都能同时到这里来");
    Foo foo = mapper.selectForUpdateById("存在的id");
    // 这里开始是临界区,只能有一个进程进来;
    assert foo != null;
    // 这里可以执行对Foo的某条记录的update操作,version = version + 1 where uniq_key = #{...}
    log.info("只有获得了'分布式锁'的进程能到这里来,执行完毕commit后会释放分布式锁,是commit而非线程结束");
}

 

posted on 2023-12-12 17:47  Silentdoer  阅读(98)  评论(0编辑  收藏  举报