/**
     * 功能锁 锁住一个代码片段
     * @param string $lockKey
     * @param callable $call
     * @param int $expire
     * @return void
     * Created by PhpStorm
     * User:jill
     * Date:2022/5/13
     * Time:3:57 PM
     * @throws ErrorException
     */
    public static function redisFunctionLock(string $lockKey, callable $call, int $expire = 10): ?array
    {

        $redis = \EasySwoole\RedisPool\Redis::defer(EnvConst::REDIS_KEY);
        $lockValue = $redis->get($lockKey);
        //验证锁状态
        if (superEmpty($lockValue)) {
            try {
                //过期时间为 0 则是上业务锁 防止同时操作一个业务 不为0 则为防止重复提交锁
                if ($expire <= 0) {
                    $redis->set($lockKey, time(), 3600);
                } else {
                    $redis->set($lockKey, time(), $expire);
                }


                $result = $call();

                if ($expire <= 0) {
                    /** 解锁 */
                    $redis->del($lockKey);
                }

            } catch (RedisException $e) {
                /** 解锁 */
                $redis->del($lockKey);
                throw new ErrorException(1000, 'redis锁调用失败');
            }
        }
        return $result ?? [];
    }
最后修改:2022 年 08 月 23 日
如果觉得我的文章对你有用,请随意赞赏