laravel的Redis锁实现

原始redis生成方式

<?php

namespace App\Utils;

use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Str;

class RedisLockUtil
{
    const EXPIRE_TIME = 10; // 秒

    /**
     * 加锁
     */
    public static function lock(string $key, int $expire = self::EXPIRE_TIME): ?string
    {
        $token = (string) Str::uuid();

        $result = Redis::set(
            $key,
            $token,
            'NX',
            'EX',
            $expire
        );

        return $result === 'OK' ? $token : null;
    }

    /**
     * 解锁(必须带 token)
     */
    public static function unlock(string $key, string $token): bool
    {
        $lua = <<<LUA
if redis.call("get", KEYS[1]) == ARGV[1] then
    return redis.call("del", KEYS[1])
else
    return 0
end
LUA;

        return Redis::eval($lua, 1, $key, $token) === 1;
    }
}

调用方式

$token = RedisLockUtil::lock('order:1', 10);

if (!$token) {
    return '系统繁忙';
}

try {
    // 业务逻辑
} finally {
    RedisLockUtil::unlock('order:1', $token);
}

这里提供一个laravel推荐使用方式
Cache::lock()

为什么 Laravel 官方 Cache::lock() 更安全?

Laravel 已经帮你封装好的

$lock = Cache::lock('order:1', 10);

if ($lock->get()) {
    try {
        //
    } finally {
        $lock->release();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

siner.li

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值