php-Symfony锁定组件未锁定-如何解决?
作者:互联网
我最近升级到了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
}
}
而且它可以防止同时运行两个命令-秒只是完成而不做任何工作.那很好.
但是在建议重构之后,它允许同时运行许多命令.这是失败的.如何防止执行?新代码:
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
}
}
注意#1:我不在乎很多服务器,仅在一个应用程序实例上.
注意2:如果进程被杀死,则新命令必须解锁并运行.
解决方法:
您必须使用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();
}
标签:locking,symfony,symfony-3-4,php 来源: https://codeday.me/bug/20191110/2014344.html