Home  >  Article  >  Database  >  How to use Redis distributed lock in Laravel

How to use Redis distributed lock in Laravel

WBOY
WBOYforward
2023-05-28 17:07:061880browse

Create lock

use IlluminateSupportFacadesCache;

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

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 () {
    // 获取无限期锁并自动释放...
});

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();
}

Or

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

Ignore the owner and force release the lock

Cache::lock('foo')->forceRelease();

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();

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!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete