<?php

namespace App\Utils;

use App\Exceptions\ServiceException;
use Illuminate\Support\Facades\Redis;

class RedisLockUtils
{
    private static $prefix = 'lock';

    public static function getKey($keyType, $extend = '')
    {
        return collect([
            self::$prefix,
            $keyType,
            $extend
        ])->filter()->implode(':');
    }

    public static function getLock($lockKey, $expireSeconds = 1, $throwException = false)
    {
        $lock = Redis::setnx($lockKey, 1);
        if (!$lock) {
            if ($throwException) {
                throw new ServiceException('操作频繁');
            }

            return false;
        }

        Redis::expire($lockKey, $expireSeconds);

        return true;
    }

    public static function deleteLock($lockKey)
    {
        return Redis::del($lockKey);
    }
}
