首页> 实战笔录 >PHP开发笔记 >ThinkPHP ThinkPHP

ThinkPHP5/tp通用 redis锁 源码分享

作者:小萝卜 2020-04-13 浏览 3629

简介快速使用 (new RedisLock ())->lock($key, $expire = 5, $num = 0) 返回true代表加锁成功 ,可以执行后面代码,否则失败; 支持重试$num次, 加锁成功后$expire秒后锁自动释放, 防止死锁 ;

tp5以上直接复制粘贴即可, 需要修改命名空间

快速使用 (new RedisLock ())->lock($key, $expire = 5, $num = 0) 返回true代表加锁成功 ,可以执行后面代码,否则失败; 

支持重试$num次,   加锁成功后$expire秒后锁自动释放,  防止死锁 ;

(new RedisLock ())->unlock($key) 解锁;

源码:

<?php
namespace Home\index\model;
use think\Cache;
class RedisLock {

    private $_redis;
    
    /**
    *这里我直接使用的$this->connect();连接的redis
    *用tp的Cache::handler();一直报错,不知道什么情况。。
    *如果有人知道请在下方留言 感激不敬
    */ 
    public function __construct() {
 
        // $handler = Cache::handler();
        // return $this->_redis = $handler->handler();
        $this->_redis = $this->connect();
    }
 
    /**
     * 获取锁
     * @param  String  $key    锁标识
     * @param  Int     $expire 锁过期时间
     * @param  Int     $num    重试次数
     * @return Boolean
     */
    public function lock($key, $expire = 5, $num = 0){
        $is_lock = $this->_redis->setnx($key, time()+$expire);
 
        if(!$is_lock) {
            //获取锁失败则重试{$num}次
            for($i = 0; $i < $num; $i++){
 
                $is_lock = $this->_redis->setnx($key, time()+$expire);
 
                if($is_lock){
                    break;
                }
                sleep(1);
            }
        }
 
        // 不能获取锁
        if(!$is_lock){
 
            // 判断锁是否过期
            $lock_time = $this->_redis->get($key);
 
            // 锁已过期,删除锁,重新获取
            if(time()>$lock_time){
                $this->unlock($key);
                $is_lock = $this->_redis->setnx($key, time()+$expire);
            }
        }
 
        return $is_lock? true : false;
    }
 
    /**
     * 释放锁
     * @param  String  $key 锁标识
     * @return Boolean
     */
    public function unlock($key){
        return $this->_redis->del($key);
    }


    /**
     * 创建redis连接
     * @return Link
     */
    private function connect(){
        try{
            $redis = new \Redis();
            $redis->connect('127.0.0.1',6379);

            $redis->auth('xiaolong123456');

        }catch(Exception $e){
            throw new Exception($e->getMessage());
            return false;
        }
        return $redis;
    }
 
}

调用:
<?php
namespace Home\index\controller;
use think\Controller;
use Home\index\model\RedisLock;
use think\Cache;

class Test extends Controller {

    public function index()
    {
        $lock = new RedisLock();
        $cv = $lock->lock('1234',15,0);
        var_dump($cv);
    }
}

使用结果:
第一次访问页面输出:true
再次刷新页面输出:false
15秒后再刷新输出:true

好了,到这里tp使用redis锁就完成了!

很赞哦! (1)

文章评论

    高端网站建设