Laravel - Cache - Managing Locks Across Processes
Sometimes, you may wish to acquire a lock in one process and release it in another process. For example, you may acquire a lock during a web request and wish to release the lock at the end of a queued job that is triggered by that request. In this scenario, you should pass the lock's scoped "owner token" to the queued job so that the job can re-instantiate the lock using the given token.
In the example below, we will dispatch a queued job if a lock is successfully acquired. In addition, we will pass the lock's owner token to the queued job via the lock's owner
method:
$podcast = Podcast::find($id);
$lock = Cache::lock('processing', 120);
if ($lock->get()) {
ProcessPodcast::dispatch($podcast, $lock->owner());
}
Within our application's ProcessPodcast
job, we can restore and release the lock using the owner token:
Cache::restoreLock('processing', $this->owner)->release();
If you would like to release a lock without respecting its current owner, you may use the forceRelease
method:
Cache::lock('processing')->forceRelease();