Symfony Messenger:使用消息接口作为处理程序__invoke type-hint

问题描述

我在Symfony 4.4应用程序中使用Symfony Messenger组件。我正在通过RabbitMQ处理异步消息,并通过Doctrine传输将失败的消息存储在数据库中。

这是Messenger配置:

framework:
    messenger:
        failure_transport: failed

        buses:
            command_bus:
                middleware:
                    - doctrine_ping_connection

        transports:
            failed: 'doctrine://default?queue_name=failed'
            async_priority_high:
                dsn: '%env(MESSENGER_TRANSPORT_DSN)%'
                retry_strategy:
                    delay: 2000
                    max_retries: 5
                    multiplier: 2
                options:
                    exchange:
                        name: high
                    queues:
                        messages_high: ~

            async_priority_low:
                dsn: '%env(MESSENGER_TRANSPORT_DSN)%'
                retry_strategy:
                    delay: 3000
                    max_retries: 3
                    multiplier: 2
                options:
                    exchange:
                        name: low
                    queues:
                        messages_low: ~

        routing:
            'App\SampleMessageButHighPriority': async_priority_high
            'App\SampleMessageInterface': async_priority_low
            'App\OtherMessage': async_priority_low

这里是一个示例处理程序,该处理程序处理了植入SampleMessageInterface接口的消息。

final class SampleMessageHandler implements MessageHandlerInterface
{
    private ProjectRepository $projectRepository;

    public function __construct(ProjectRepository $projectRepository)
    {
        $this->projectRepository = $projectRepository;
    }

    public function __invoke(SampleMessageInterface $message): void
    {
        $project = $this->projectRepository->find($message->getProjectId()->toString());

        if ($project === null) {
            return;
        }

        $this->someProcessor->__invoke($project);
    }
}

一切正常,然后再面对任何消息失败。尝试重试或显示失败的消息失败后,问题开始显示。让我们尝试一下php bin/console messenger:failed:show命令:

结果:

In PhpSerializer.php line 64:
                                                                               
  Cannot instantiate interface App\SampleMessageInterface                                                            

我猜想Symfony需要反序列化失败的消息,该消息先前已序列化并存储在数据库中,但是由于它是一个接口而无法做到。

我该如何解决?有什么方法可以使用类实现而不是接口来序列化失败的消息?

解决方法

失败的消息按序列存储在数据库中。当您重试或显示这些消息时,它们会反序列化。

只需将接口SampleMessageInterface替换为类SampleMessage

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...