如何停止MessageHandler进程?
die
或 exit
命令使用此 MessageHandler 重新启动 docker 容器
附:我可以用嵌套 if 来解决它,但也许有聪明的解决方案?
#[AsMessageHandler]
class SongArtworkCrawlingMessageHandler
{
public function __construct(
private readonly EntityManagerInterface $entityManager,
private readonly LoggerInterface $logger,
private readonly MessageBusInterface $messageBus,
#[Autowire('%kernel.project_dir%')]
private string $projectDir,
) {
}
public function __invoke(SongArtworkCrawlingMessage $crawlingMessage)
{
$urlQuery = str_replace(' ', '+', $crawlingMessage->getSongTitleAndArtist());
$urlQuery = str_replace('_', '+', $urlQuery);
$url = 'https://www.radioskonto.lv/search?query='.$urlQuery;
$browser = Client::createChromeClient();
$songArtwork = new SongArtwork();
$browser->request('GET', $url);
sleep(2);
if ($browser->getCrawler()->filter('.css-0 > a')->count() === 0) {
$songArtworkNotFound = new SongArtworkNotFound();
$songArtworkNotFound->setSongArtistTitle($crawlingMessage->getSongTitleAndArtist());
$songArtworkNotFound->setFailReason('No Data to crawl');
$songArtworkNotFound->setCreatedAt(new \DateTimeImmutable());
$this->entityManager->persist($songArtworkNotFound);
$this->entityManager->flush();
die('No data to crawl - '.$url); // <<<---- PROBLEM IS HERE
/// OR
exit('No data to crawl - '.$url);
}
// CODE with Crawling and saving process below
}
要在不重新启动 Docker 容器的情况下正常停止 MessageHandler 进程,请避免使用
die
或 exit
,因为它们会强制终止进程,可能会导致 Docker 容器生命周期出现问题。最好创建自定义异常。
class SongArtworkNotFoundException extends \Exception
{
public function __construct($message = "No data to crawl", $code = 0, Exception $previous = null)
{
parent::__construct($message, $code, $previous);
}
}
所以你可以这样做:
...
if ($browser->getCrawler()->filter('.css-0 > a')->count() === 0) {
$songArtworkNotFound = new SongArtworkNotFound();
$songArtworkNotFound->setSongArtistTitle($crawlingMessage->getSongTitleAndArtist());
$songArtworkNotFound->setFailReason('No Data to crawl');
$songArtworkNotFound->setCreatedAt(new \DateTimeImmutable());
$this->entityManager->persist($songArtworkNotFound);
$this->entityManager->flush();
throw new SongArtworkNotFoundException('No data to crawl - ' . $url);
}
...