The use of laravel redis distributed lock

Time:2021-7-5

Create lock

use Illuminate\Support\Facades\Cache;

$lock = Cache::lock('foo', 10);
if ($lock->get()) {
    //Processing business logic
    sleep(3);
    $lock->release();
}

Acquire indefinite lock and release automatically

getMethod can receive a closure. After the closure is executed, laravel will automatically release the lock.

Cache::lock('foo')->get(function () {
    //Get indefinite lock and release automatically
});

Acquire lock in specified time

use Illuminate\Contracts\Cache\LockTimeoutException;

$lock = Cache::lock('foo', 10);
try {
    $lock->block(5);
    Echo "successfully acquire lock within 5 seconds...";
} catch (LockTimeoutException $e) {
    Echo "failed to acquire lock within 5 seconds...";
} finally {
    optional($lock)->release();
}

Another way of writing:

Cache::lock('foo', 10)->block(5, function () {
    Echo "successfully acquire lock within 5 seconds...";
});

Force release lock regardless of owner

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

Cross process management lock

//In the controller
$podcast = Podcast::find($id);
$lock = Cache::lock('foo', 120);
if ($result = $lock->get()) {
    ProcessPodcast::dispatch($podcast, $lock->owner());
}
//In the queue task
//Use the lock name and owner to retrieve the lock instance and release it
Cache::restoreLock('foo', $this->owner)->release();