Redis5 基于Lua实现分布式排它锁

直接上PHP代码

public function index(){
       $token=uniqid("lock");


       if ($this->lock($token)){

           Redis::incr("count");

           $this->unlock($token);


           return "抢到了";
       }

       return "等着吧";

   }

   public function lock($token){
       $set_sh="
            local isOK=redis.call('setnx',KEYS[1],ARGV[1])
            redis.call('expire',KEYS[1],ARGV[2])
            return isOK
       ";
       return Redis::eval($set_sh,1,"my:lock",$token,2);
   }

   public function unlock($token){
        $sh="if redis.call('get',KEYS[1]) == ARGV[1]
         
         then 
            return redis.call('del',KEYS[1]) 
         else 
            return  0 
         end" ;
      return Redis::eval($sh,1,"my:lock",$token);

   }

 

 详细说明来源

 

 https://learnku.com/articles/4211/unlock-the-correct-position-of-the-redis-lock#reply111774

!!!

posted @ 2019-10-09 22:06  万隆  阅读(278)  评论(0编辑  收藏  举报