Example #1
0
 /**
  * 上锁
  *
  * @param string $key
  * @return boolean
  */
 public function acquire($name)
 {
     $key = $this->getKey($name);
     $time = time();
     while (time() - $time < $this->max_timeout) {
         $lockValue = time() + $this->timeout;
         if ($this->redis->set($key, $lockValue, "EX", $this->timeout, "NX")) {
             // 加锁成功。
             return true;
         }
         // 未能加锁成功。
         // 检查当前锁是否已过期,并重新锁定。
         if ($this->redis->get($key) < time() && $this->redis->getset($key, $lockValue) < time()) {
             $this->redis->expire($key, $this->timeout);
             return true;
         }
         usleep($this->retry_wait_usec);
     }
     return false;
 }