Symfony Lock 组件无法锁定 – 如何修复?

tro*_*war 6 php locking symfony symfony-3.4

我最近升级到 Symfony 3.4.x,由于弃用警告而重构 LockHandler 并陷入奇怪的行为。

重构前的命令代码:

class FooCommand
{
    protected function configure() { /* ... does not matter ... */ }
    protected function lock() : bool
    {
        $resource = $this->getName();
        $lock     = new \Symfony\Component\Filesystem\LockHandler($resource);

        return $lock->lock();
    }
    protected function execute()
    {
        if (!$this->lock()) return 0;

        // Execute some task
    }
}
Run Code Online (Sandbox Code Playgroud)

并且它可以防止同时运行两个命令 - 第二个只是完成而不做工作。那很好。

但是在建议重构之后,它允许同时运行许多命令。这是失败。如何防止执行?新代码:

class FooCommand
{
    protected function configure() { /* ... does not matter ... */ }
    protected function lock() : bool
    {
        $resource = $this->getName();
        $store    = new \Symfony\Component\Lock\FlockStore(sys_get_temp_dir());
        $factory  = new \Symfony\Component\Lock\Factory($store);
        $lock     = $factory->createLock($resource);

        return $lock->acquire();
    }
    protected function execute()
    {
        if (!$this->lock()) return 0;

        // Execute some task
    }
}
Run Code Online (Sandbox Code Playgroud)

NB #1:我不关心很多服务器,只关心一个应用程序实例。

注意#2:如果进程被杀死,那么新命令必须解锁并运行。

Moh*_*nda 7

您必须使用 LockableTrait 特性

    use Symfony\Component\Console\Command\LockableTrait;
    use Symfony\Component\Console\Command\Command

    class FooCommand  extends Command
    {
        use LockableTrait;
.....
protected function execute(InputInterface $input, OutputInterface $output)
    {
        if (!$this->lock()) {
            $output->writeln('The command is already running in another process.');

            return 0;
        }
// If you prefer to wait until the lock is released, use this:
        // $this->lock(null, true);

        // ...

        // if not released explicitly, Symfony releases the lock
        // automatically when the execution of the command ends
        $this->release();

}
Run Code Online (Sandbox Code Playgroud)