Home > Database > Redis > body text

How to use Redis distributed lock in Laravel

WBOY
Release: 2023-05-28 17:07:06
forward
1962 people have browsed it

Create lock

use IlluminateSupportFacadesCache;

$lock = Cache::lock('foo', 10);
if ($lock->get()) {
    // 处理业务逻辑
    sleep(3);
    $lock->release();
}
Copy after login

Get an indefinite lock and automatically release it

The get method can receive a closure. After the closure is executed, Laravel will automatically release the lock.

Cache::lock('foo')->get(function () {
    // 获取无限期锁并自动释放...
});
Copy after login

Acquire the lock within the specified time

use IlluminateContractsCacheLockTimeoutException;

$lock = Cache::lock('foo', 10);
try {
    $lock->block(5);
    echo "5秒时间内成功获取锁...";
} catch (LockTimeoutException $e) {
    echo "5秒时间内获取锁失败...";
} finally {
    optional($lock)->release();
}
Copy after login

Or

Cache::lock('foo', 10)->block(5, function () {
    echo "5秒时间内成功获取锁...";
});
Copy after login

Ignore the owner and force release the lock

Cache::lock('foo')->forceRelease();
Copy after login

Cross-process management lock

// 控制器中...
$podcast = Podcast::find($id);
$lock = Cache::lock('foo', 120);
if ($result = $lock->get()) {
    ProcessPodcast::dispatch($podcast, $lock->owner());
}

// 队列任务中...
// 使用锁名称和拥有者重新获取锁实例后再释放
Cache::restoreLock('foo', $this->owner)->release();
Copy after login

The above is the detailed content of How to use Redis distributed lock in Laravel. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template