Redis implements pessimistic locking.
The principle is to go in and grab the lock. If the grab fails, wait a second to grab it, wait another second to grab it, and so on and so forth.
To unlock is to delete the corresponding key.
/** * Implement redis pessimistic locking * User: babytuo */ Class RedisLock { public $expire = 2; public function test(){ $this->lock("test1"); echo "111"; } public function lock($key){ $redis = self::createRedisObj(); $now = time(); /* * Understand setnx If the given key already exists, SETNX does nothing. SETNX is shorthand for "SET if Not eXists" (SET if not present). */ // Grab the lock. $isLock = $redis ->setnx( $key , time () + $this ->expire); // Set as the expiration time. //不成功 while ( ! $isLock) { $now++; $time = $now + $this->expire; // Recreate $lock = $redis ->setnx( $key , $time ); if ( $lock == 1 || ( $now > $redis ->get( $key ) && $now > $redis - >getset( $key , $time ))) { // After the lock contention is successful, set a new expiration time. break ; } else { sleep(1);//0.5s } } return true; } /** * Unlock * @param type $flag * @return boolean */ public function unlock($key) { $redis = self::createRedisObj(); $redis->del($key); return true; } /** * Check if the lock exists * @param $key * @return bool */ public function checklock($key){ $redis = self::createRedisObj(); return $redis->exists($key); } public static $_redis ; /* * * Create a redis object. * @return Redis */ public static function createRedisObj(){ if ( ! self:: $_redis ){ $redis = new Redis(); $info = Yii::app()->cache->servers[0]; // read config $host = $info ["host" ]; $port = $info ["port" ]; $redis ->connect( $host , $port ); $redis_db = Yii::app()->settings-> get('system' , 'redis_db'); // Set the default library $redis->select($redis_db); self::$_redis = $redis; } return self::$_redis; } }