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();
    }
}
相关推荐
周小码2 天前
10分钟搭建管理后台:laravel-admin实战入门
php·laravel
DigitalOcean13 天前
Laravel 开发者已在 DigitalOcean 上开通超过 10 万台服务器
前端·laravel
zzqssliu21 天前
基于Laravel + Express.js的代购系统多语言多货币架构设计
javascript·express·laravel
zuowei288921 天前
Laravel 9.x核心特性全解析
php·laravel
2501_9127840821 天前
跨境电商独立站技术选型:为什么React+Vue+Laravel成为主流?
vue.js·react.js·laravel·taocarts
右耳朵猫AI25 天前
PHP周刊2026W22 | WordPress 7.0发布、Laravel 13.10.0、Polyfill 1.38.1、Symfony 8.1
php·laravel·symfony
2501_912784081 个月前
跨境电商独立站的多语言架构设计:基于 Laravel + Vue.js 的实践
vue.js·php·laravel·跨境电商·taocarts
JaguarJack1 个月前
免费可商用 PHP 管理后台 CatchAdmin V5.3.1 发布 后台打包直降 5s 内
后端·php·laravel
ELI_He9991 个月前
Laravel Sail
php·laravel
AI行业学习1 个月前
CC-Switch 下载、安装与使用配置指南【2026.5.29】
java·开发语言·vscode·python·eclipse·laravel