PHP守护进程与原则2


PHP Daemon with Doctrine 2

我有一个PHP守护进程正在运行:

while (true) {
    $tasks = $this->tasksFinder->findDueTasks();
    foreach ($tasks as $task) {
        try {
            $handlerClass = $task->getHandlerClass();
            /** @var AbstractTaskHandler $handler */
            $handler = new $handlerClass(...$task->getArguments());
            $handler->setEntityManager($this->getEm());
            $handler->handle();
            $this->getEm()->remove($task);
        } catch (Exception $e) {
            $this->logger->error("{$e->getMessage()}'n{$e->getTraceAsString()}");
            $task->setDisabled(true);
            $this->getEm()->persist($task);
        }
    }
    $this->getEm()->flush();
    sleep(1);
}
在处理程序类内部(将从守护进程中获取)将完成一些调试工作。例如:
$this->getEm()->transactional(function (EntityManager $em) {
    $repository = $em->getRepository(UserUnit::class);
    /** @var UserUnit $entity */
    $entity = $repository->findOneBy(['user' => 1, 'type' => Enum::ORC]);
    $em->lock($entity, LockMode::PESSIMISTIC_WRITE);
    $entity->increase(1);
});

所以玩家1的条目orc将增加1。假设我们已经有了10个半兽人。创建一个任务并由守护进程处理,结果为11。一切正常,但是如果我手动将条目设置为0并在不重新启动守护进程的情况下创建一个任务,那么它也将是11。所以看起来守护进程正在使用缓存!?我说的对吗?如何解决这个问题?清除缓存?

$this->getEm()->flush();解决问题后再呼叫$this->getEm()->clear();。调用clear后,对象将再次从数据库加载,而不是由Doctrine的身份映射提供服务。