Stiphle\Storage\Redis::lock PHP Method

lock() public method

{@inheritDoc}
public lock ( $key )
    public function lock($key)
    {
        $start = microtime(true);
        while (is_null($this->redisClient->set($this->getLockKey($key), 'LOCKED', 'PX', 3600, 'NX'))) {
            $passed = (microtime(true) - $start) * 1000;
            if ($passed > $this->lockWaitTimeout) {
                throw new LockWaitTimeoutException();
            }
            usleep(100);
        }
    }

Usage Example

Example #1
0
 public function testLockThrowsLockWaitTimeoutException()
 {
     $redisClient = $this->getMockBuilder(\Predis\Client::class)->setMethods(['set'])->getMock();
     $redisClient->expects($this->at(0))->method('set')->with('dave::LOCK', 'LOCKED', 'PX', 3600, 'NX')->will($this->returnValue(1));
     $redisClient->expects($this->any())->method('set')->with('dave::LOCK', 'LOCKED', 'PX', 3600, 'NX')->will($this->returnValue(null));
     $this->expectException(\Stiphle\Storage\LockWaitTimeoutException::class);
     $storage = new Redis($redisClient);
     $storage->lock('dave');
     $storage->lock('dave');
 }