The following column Laravel Tutorial will introduce to you how to use Redis distributed lock (atomic lock lock block release) in laravel. I hope it will be helpful to friends in need!
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. [Related recommendations: laravel video tutorial]
Cache::lock('foo')->get(function () { // 获取无限期锁并自动释放... });
Get 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 to 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 Detailed explanation of how to use Redis distributed locks in Laravel (with code examples). For more information, please follow other related articles on the PHP Chinese website!