Redis implements pessimistic locks.
Principle, in the grab lock, Rob failed to wait a second to rob, and then another second to rob, so repeated circulation.
Unlocking means deleting the corresponding key.
/** * Realize Redis pessimistic lock * User:babytuo*/ClassRedislock { Public $expire= 2; Public functionTest () {$this->lock ("Test1"); Echo"111"; } Public functionLock$key){ $redis= Self::createredisobj (); $now= Time(); /** Understanding SETNX if a given key already exists, then SETNX does not do any action. Setnx is a shorthand for "set if not EXists" (set if it does not exist). */ //grab the lock. $isLock=$redis->SETNX ($key, Time() +$this->expire);//set to the expiration time. Not successful while( !$isLock) { $now++; $time=$now+$this-expire; //and re-create $lock=$redis->SETNX ($key,$time); if($lock= = 1 | | ($now>$redis->get ($key) &&$now>$redis->getset ($key,$time))) {//after the lock is successful, set a new expiration time. Break; } Else { Sleep(1);//0.5s } } return true; } /** * unlock * @param type $flag * @return Boolean*/ Public functionUnlock$key) { $redis= Self::createredisobj (); $redis->del ($key); return true; } /** * Check if the lock exists * @param $key * @return bool*/ Public functionChecklock ($key){ $redis= Self::createredisobj (); return $redis->exists ($key); } Public Static $_redis; /** * Create a Redis object. * @return Redis*/ Public Static functioncreateredisobj () {if(! Self::$_redis){ $redis=NewRedis (); $info= Yii::app ()->cache->servers[0];//Read Configuration $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; } returnSelf::$_redis; }}
Common application concurrency Lock for PHP redis. (Pessimistic Lock)