<?php
namespace Lock;
/**
 * User: liuyuzhen
 * Date: 2018/8/20
 * Time: 10:48
 * Description:
 */
class RedisLock implements \Lock\ILock{

    private $lockRedis ;
    public function __construct()
    {

        $this->lockRedis = \Redis\Db0\LockRedisModel::getInstance();
    }

    public function getLock($key, $timeout=self::EXPIRE)
    {
        $waitime = 20000;
        $totalWaitime = 0;
        $time = $timeout*1000000;
        while ($totalWaitime < $time && false == $this->lockRedis->update($key, 1, $timeout)){
            usleep($waitime);
            $totalWaitime += $waitime;
        }
        if ($totalWaitime >= $time){
            \Our\Log::getInstance()->write($key.' can not get lock for waiting '.$timeout.'s.');
            throw new Exception('can not get lock for waiting '.$timeout.'s.');
        }
    }

    public function releaseLock($key)
    {
        $this->lockRedis->tableDel($key);
    }

    /**
     * 类实例
     *
     */
    private static $_instance = null;

    /**
     * 获取类实例
     */
    public static function getInstance() {
        if (!(self::$_instance instanceof self)) {
            self::$_instance = new self();
        }

        return self::$_instance;
    }
}