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();
    }
}
相关推荐
Shi_haoliu5 天前
SolidTime 本地与服务器环境搭建指南(Laragon + Laravel + Vue3 + PostgreSQL)
服务器·vue.js·ai·postgresql·php·laravel
是乐乐啊呀11 天前
laravel
php·laravel
小代码201613 天前
ubuntu vscode docker php 环境搭建
vscode·ubuntu·docker·php·laravel
lskblog13 天前
PHP中正确处理HTTP响应:从原始响应到JSON数组的完整指南
http·json·php·laravel
JaguarJack14 天前
前后端分离框架 CatchAdmin V5 beta.2 发布 插件化与开发效率的进一步提升
后端·php·laravel
catchadmin16 天前
使用 Laravel Workflow 作为 MCP 工具提供给 AI 客户端
人工智能·php·laravel
catchadmin18 天前
当遇见 CatchAdmin V5-模块化设计重新定义 Laravel 后台开发
php·laravel
北漂燕郊杨哥18 天前
Laravel中Tymon\JWTAuth 的用法示例
php·laravel
BingoGo19 天前
使用 Laravel Workflow 作为 MCP 工具提供给 AI 客户端
后端·php·laravel