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();
    }
}
相关推荐
m0_7482299911 小时前
Laravel 2.x:框架的早期特性解析
php·laravel
m0_748229992 天前
Laravel 6.X 核心特性全解析
php·laravel
m0_748229995 天前
Laravel高效入门:关键路径全解析
php·laravel
强化试剂7 天前
Acridinium-Biotin,吖啶生物素偶联物在化学发光免疫分析中的应用逻辑
erlang·laravel·composer
Shi_haoliu14 天前
SolidTime 在 Rocky Linux 9.5 上的完整部署流程
linux·运维·nginx·postgresql·vue·php·laravel
hteng16 天前
逮住那个幽灵:Laravel+Supervisor后台任务高并发下 PDO Error 2014 的排查实录
php·laravel
Shi_haoliu1 个月前
SolidTime 本地与服务器环境搭建指南(Laragon + Laravel + Vue3 + PostgreSQL)
服务器·vue.js·ai·postgresql·php·laravel
是乐乐啊呀1 个月前
laravel
php·laravel
小代码20161 个月前
ubuntu vscode docker php 环境搭建
vscode·ubuntu·docker·php·laravel