我正在使用beanstalkd任务队列来推迟一些繁重的Doctrine操作,但这可以在RabbitMQ等任何其他类似的系统中重现。
$entityManager = $this->getDoctrine()->getManager();
$productEntity = new Product();
$productEntity->setData('somedata');
$entityManager->persist($productEntity);
// This method is blocking, right? The execution will not continue until the
// data is inserted into the database
$entityManager->flush();
// At this point the data should be already in the database
// $productEntity->getId() returns a valid auto-incremented integer
// So we pass the job to the task queue, which will be executed immediately in the worker
$beanstalkdService->put(
json_encode([
'command'=>'some:heavy:task',
'product_id' => $productEntity->getId()
)
);
$entityManager = $this->getDoctrine()->getManager();
while(true){
$job = json_decode($beanstalkd->reserve());
if ($job['command'] === 'some:heavy:task'){
$productEntity = $entityManager->find('\Path\To\Product, $job['product_id']);
}
}
这条线
如果立即执行,$entityManager->find('\Path\To\Product, $job['product_id']);
会返回null
无论其
如果我在执行之前添加一个小延迟,比如
sleep(1);
$entityManager->find('\Path\To\Product, $job['product_id']);
然后实体按照预期返回!
为什么没有延迟就无法访问记录?不是flush()方法阻塞,所以除非将记录插入数据库,否则执行不会继续?