我正在嘗試爲事件設置後臺處理系統。我使用本教程:https://informulate.com/blog/symfony/high-performance-through-asynch-operations-using-symfony-background-processing/異步事件
我跟所有的步驟,但我有2個問題:
- 在命令,我不知道是否給調度員的事件對象是事件實體或事件默認類。我認爲它應該是默認的類,但如果是這樣,我怎麼能從我的訂閱服務器中的Event實體獲取數據?
- 我的訂戶似乎沒有得到這個活動。
認購人:
class QCModifiedSubscriber implements EventSubscriberInterface
{
public function __construct(EntityManagerInterface $em, CorrectionReponseService $correctionReponse)
{
$this->em = $em;
$this->correctionReponse = $correctionReponse;
}
public static function getSubscribedEvents()
{
// Liste des évènements écoutés et méthodes à appeler
return array(
'qc.modified' => 'calculStats'
);
}
public function calculStats(Event $event)
{
$data = $event->getData();
$QC = $this->em->getRepository(QC::class)->find($data['qcId']);
$this->correctionReponse->correctionReponsesOfQC($QC);
}
}
services.yml:
services:
PACES\ColleBundle\EventListener\QCModifiedSubscriber:
tags:
- { name: 'kernel.event_subscriber'}
命令:
protected function execute(InputInterface $input, OutputInterface $output)
{
$em = $this->getContainer()->get('doctrine')->getManager();
$dispatcher = new EventDispatcher();
while (true) {
$processId = rand(0, 999999999);
# attempts to claim a single event, returns it if successful. may return multiple events.
// note: $processId is some unique id to this process, helps prevent race conditions (see below)
$events = $em->getRepository(Event::class)->claimEvent($processId);
# no events to process, so break out of loop.
if (count($events) === 0) {
break;
}
# iterate over each event to be processed, typically just 1.
foreach ($events as $eventEntity) {
$output->write("Processing id: {$eventEntity->getId()}" . PHP_EOL);
# create the event...
$event = new \Symfony\Component\EventDispatcher\Event($eventEntity);
try {
# dispatch the event!
$dispatcher->dispatch($eventEntity->getName(), $event);
# if we made it here we were successful, mark as processed
$eventEntity->setProcessed(1);
} catch (\Exception $e) {
$eventEntity->setError((string)$e);
}
$em->persist($eventEntity);
$em->flush();
}
}
}
事件實體exactl y和教程中的一樣。
非常感謝您的詳細解答。它現在工作完美! –
很高興你的工作!這個文檔第一次讓我失望了,而且我沒有意識到從頭開始創建一個新的'EventDispatcher'就像更多的獨立工作一樣。 –