Evolution of redis lock

      Daily work will always be high concurrency scenarios, the need to achieve locking mechanism to ensure the sequence of, let's step by step to achieve the next single Redis Redis completely reliable lock (ps: If Redis cluster, then it is a master-slave switch the problem of lock failure, to solve this problem, then more trouble, not discussed here, existing solutions have redlock, we can look to achieve its principle)

Redis lock First Edition (php realization):

    //加锁
    public function lock($key)
    {
        $redisConnect = Redis::connection();
        $v = $redisConnect->get($key);
        if ($v == 1) {
            return false;
        }
        $res = $redisConnect->setex($key);
        return (bool)$res;
    }

    //解锁
    public function unlock($key)
    {
        $redisConnect = Redis::connection();
        return $redisConnect->del($key);
    }

 

A version of the question: If, after locking process is interrupted, it will deadlock

 

Version two, set the lock timeout to solve a problem version

    public function lock($key, $seconds)
    {
        $redisConnect = Redis::connection();
        $v = $redisConnect->get($key);
        if ($v == 1) {
            return false;
        }
        $res = $redisConnect->setex($key, $seconds, 1);
        return (bool)$res;
    }

    //解锁
    public function unlock($key)
    {
        $redisConnect = Redis::connection();
        return $redisConnect->del($key);
    }

 

The second version of the problem: set timeout, but there is a scene, a lock after a time-out to have not been performed, this time to re-lock can lock failure b, then finished it will put a plus b locks delete. In the final analysis the problem lies in the different processes plus the lock is no different.

 

Version three: solve the problem of two versions can be added to a unique set of locks in the set time, remove the lock in time, if we find a unique value is not set up, do not delete the lock changed and the description of this operation has been atomicity was destroyed, insurance purposes need to roll back the current kind.

// todo scratch

 

Guess you like

Origin www.cnblogs.com/tobemaster/p/11350892.html