PHP uses Redis to add locks

Source: Internet
Author: User
Tags auth redis

1.redis Lock introduces this class

<?php/** * Redis lock Operation class * date:2016-06-30 * author:fdipzone * ver:1.0 * * FUNC: * Public lock get
    Lock * Public Unlock release lock * Private Connect * * class Redislock {//class start Private $_config;

    Public $_redis; /** * Initialization * @param Array $config Redis Connection Set/Public function __construct ($config =array ()) {$th
        Is->_config = $config;
    $this->_redis = $this->connect ();
     /** * Acquire lock * @param String $key Lock ID * @param Int $expire Lock expiration * @return Boolean

        * * Public Function Lock ($key, $expire =5) {$is _lock = $this->_redis->setnx ($key, Time () + $expire);

            Cannot get lock if (! $is _lock) {//To determine whether the lock expires $lock _time = $this->_redis->get ($key);
                The lock is expired, the lock is removed, and the If (Time () > $lock _time) {$this->unlock ($key) is retrieved;
$is _lock = $this->_redis->setnx ($key, Time () + $expire);            } return $is _lock?
    True:false;
        /** * Release lock * @param String $key Lock Identification * @return Boolean/Public Function unlock ($key) {
    return $this->_redis->del ($key); /** * Create redis Connection * @return Link/private Function connect () {try{$redis =
            New Redis (); $redis->connect ($this->_config[' host '), $this->_config[' Port ', $this->_config[' timeout '], $this->
            _config[' reserved '], $this->_config[' retry_interval ']);
            if (!empty ($this->_config[' auth ')) {$redis->auth ($this->_config[' auth '));
        $redis->select ($this->_config[' index '));
            }catch (Redisexception $e) {throw new Exception ($e->getmessage ());
        return false;
    return $redis;

 }//Class end


2. Call

        $oRedisLock = new Redislock ($config);

      Get the lock, try 3 for
        ($i =0 $i <=3; $i + +) {
            $is _lock = $oRedisLock->lock ($key, 2);
            if ($is _lock) {break
                ;
            }
        }

        if ($is _lock) {

            //dosth logic

            /release lock
            $is _lock = $oRedisLock->unlock ($key);
            
        } else{
        }

3. A simpler way

SET key value [EX seconds] [PX milliseconds] [nx| XX]

Starting with the version of Redis 2.6.12, the behavior of the SET command can be modified by a series of parameters: EX Second: The SET key expires in second seconds. The SET key value EX second effect is equivalent to Setex key second value. PX millisecond: Sets the key's expiration time to millisecond milliseconds. The SET key value PX millisecond effect is equivalent to Psetex key millisecond value. NX: The key is set to operate only if the key does not exist. The SET key value NX effect is equivalent to Setnx key value. XX: The key is set to operate only if the key already exists.

1, client A requests the server to set the value of the key, if the success of the set to indicate the success of the lock
    2, Client B also to request the server to set the value of the key, if the return failure, then on behalf of Lock failed
    3, client a executes code completion, delete the lock
    4, Client B waits for a while to request the value of the set key, set success
    5, Client B execute code completion, delete the lock

    $redis->set ($key, $value, Array (' NX ', ' ex ' => $ttl));  Ex represents seconds



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.