Laravel cache lock already locked?
P粉818561682
P粉818561682 2024-03-27 13:28:19
0
1
475

TLDR: How to check if a Laravel atomic lock is locked without locking it and checking the return value of the $lock->get() call?

I have multiple Laravel commands executed through the scheduler. A command is not scheduled and if it is running, no other commands should be run. So I introduced atomic cache lock from Laravel like this:

private function checkSetupRunning(){
    $lock = Cache::store('locks')->getStore()->lock(
        self::RUNNING_KEY, // name for the lock
        owner: self::class
    );

    if ($lock->get(fn() => null) === false) {
        throw new SetupRunningException();
    }
}

This does work as expected, however, when running multiple of these commands in parallel, sometimes it seems that the lock has been acquired via the checkSetupRunning function of another command and therefore fails, even though the setup-command is not running.

So I need a way to check if the lock has been acquired without locking the lock. I checked the documentation and some code but couldn't find a solution.

P粉818561682
P粉818561682

reply all(1)
P粉604507867

This is how we found it

 public static function getCacheLockOwner(string $key): string|false
 {
        return Cache::lockConnection()->client()->get(Cache::getPrefix().$key);
 }

It returns the lock owner (a string) if present, otherwise it returns false.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!