Redis 分布式锁解决方案

栏目: Redis · 发布时间: 7年前

内容简介:Redis 分布式锁解决方案

在论坛上找到各种版本,应用到项目出运行不了,各种报错。今天自己重新编写调试测试,运行成功。

  • PHP redis使用phpredis
  • 参考redis官方资料
  • 具体代码

    <?php
    namespace app\common\service;
    
    /**
     *
     * redis 加锁 --单 Redis 实例实现分布式锁
     *
     * -- 分布式请使用:Redlock:https://github.com/ronnylt/redlock-php
     * -- 详情参考: http://www.redis.cn/topics/distlock.html
     *
     * @package app\common\service
     */
    class RedisLock
    {
        const LOCK_SUCCESS = 'OK';
        const IF_NOT_EXISTS = 'NX';
        const MILLISECOND_EXPIRE_TIME = 'PX';
        const EXPIRE_TIME = 60000; // millisecond => 60s
        const LOCK_VALUE = 1;
    
            /**
             * 加锁
             * @param $redis object
             * @param $key
             * @param string $expire_time 60000
             */
            public static function lock($redis, $key, $expire_time='')
            {
                if (empty($expire_time)) {
                        $expire_time = self::EXPIRE_TIME;
                }
    
                $result = $redis->set($key, self::LOCK_VALUE, [self::IF_NOT_EXISTS, self::MILLISECOND_EXPIRE_TIME => $expire_time]);
    
                return self::LOCK_SUCCESS === (string)$result;
            }
    
            /**
             * 解锁
             *
             * 参考: https://github.com/phpredis/phpredis/blob/develop/tests/RedisTest.php
             * @param $redis
             * @param $key
             */
            public static function unlock($redis, $key)
            {
                $lua =<<<EOT
    if redis.call("get",KEYS[1]) == ARGV[1] then
        return redis.call("del",KEYS[1])
    else
        return 0
    end
    EOT;
                $result = $redis->eval($lua, array($key, self::LOCK_VALUE), 1);
                return $result;
        }
    }

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Data Structures and Algorithm Analysis in Java

Data Structures and Algorithm Analysis in Java

Mark A. Weiss / Pearson / 2011-11-18 / GBP 129.99

Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course wa......一起来看看 《Data Structures and Algorithm Analysis in Java》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具