美文网首页
Redis 分布式锁

Redis 分布式锁

作者: 我叫钱多多_ | 来源:发表于2018-09-12 16:53 被阅读0次

    1.2 基于Redis的分布式锁

    1.2.2 实现原理: 基于乐观锁,即在提交事务前检查数据版本是否被更新,若被更新则进行操作回滚;

    1.2.3 核心代码:

           /**
             * @Description: 尝试获得某资源的锁,获取成功为true,否则为false
             * @Param: [source] 资源名称
             * @Return: boolean
             * @Author: Guimu
             * @Date: 2018/8/8  下午5:53
             */
            public boolean getLock(String source) {
                SessionCallback sc = new SessionCallback() {
                    @Override
                    public List<Object> execute(RedisOperations operations) throws DataAccessException {
                        operations.watch(source);//开始观察资源
                        boolean flag = null == operations.opsForValue().get(source);//资源是否可用
                        List<Object> rs = null;
                        if (flag) {//资源可用
                            operations.multi();//开启事务
                            //占用资源
                            operations.opsForValue().set(source, Thread.currentThread().getName(), 120, TimeUnit.SECONDS);
                            rs = operations.exec();
                        }
                        return rs;
                    }
                };
                List<Object> result = (List<Object>) tool.execute(sc);
                return null != result && result.isEmpty();
            }
    

    1.2.4 集群中分布式锁的应用场景:

    image.png

    相关文章

      网友评论

          本文标题:Redis 分布式锁

          本文链接:https://www.haomeiwen.com/subject/juqbgftx.html