laravel的Redis锁实现

原始redis生成方式

php 复制代码
<?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;
    }
}

调用方式

php 复制代码
$token = RedisLockUtil::lock('order:1', 10);

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

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

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

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

Laravel 已经帮你封装好的

php 复制代码
$lock = Cache::lock('order:1', 10);

if ($lock->get()) {
    try {
        //
    } finally {
        $lock->release();
    }
}
相关推荐
cch89182 天前
Laravel vs ThinkPHP3.x:现代框架对决
php·laravel
jwn9992 天前
Laravel6.x核心特性全解析
开发语言·php·laravel
jwn9993 天前
Laravel2.x经典特性回顾
开发语言·php·laravel
cch89184 天前
Laravel vs ThinkPHP:PHP框架终极对决
android·php·laravel
cch89184 天前
Laravel vs 主流PHP框架:终极对决
开发语言·php·laravel
jwn9995 天前
Laravel11.x新特性全解析
android·开发语言·php·laravel
jwn9995 天前
Laravel 8.x新特性全解析
php·laravel
jwn9996 天前
Laravel5.x核心特性全解析
android·php·laravel
jwn9996 天前
Laravel 7.x核心特性全解析
php·laravel