<?php


namespace App\Cache\Lock;


use App\Consts\BaseConst;
use App\Libs\Utils;
use Illuminate\Support\Facades\Redis;

/**
 * 命令参考链接： http://doc.redisfans.com/string/set.html
 * 命令 SET resource-name anystring NX EX max-lock-time 是一种在 Redis 中实现锁的简单方法。
 * Class LockCache
 * @package App\Cache\Lock
 */
class LockCache
{
    /**
     * @param     $token
     * @param int $seconds
     * @return mixed
     */
    public static function getLock($token, $seconds = BaseConst::LOCK_DEFAULT_SECONDS)
    {
        $cacheKey = Utils::getCacheKey('lock.token', [$token]);
        return Redis::set($cacheKey, $token, 'nx', 'ex', $seconds);
    }

    /**
     * @param $token
     * @return int
     */
    public static function releaseLock($token)
    {
        $cacheKey = Utils::getCacheKey('lock.token', [$token]);
        $result   = Redis::get($cacheKey);
        if ($result === $token) {
            return Redis::del($cacheKey);
        }

        return 0;
    }
}