Magento2消息队列启动消费者报期望字符串传null错误
Magento 2 消息队列消费者启动类型错误修复方案
问题现象
- 消息写入逻辑正常,可在
queue_message数据库表中查询到已写入的消息 - 执行
php bin/magento queue:consumers:start erp.queue.order启动消费者时抛出异常:
Type Error occurred when creating object: Magento\Framework\MessageQueue\Consumer\Config\Data, Argument 2 passed to Magento\Framework\Reflection\TypeProcessor::resolveFullyQualifiedClassName() must be of the type string, null given, called in /Users/timog/Sites/magento2.local/vendor/magento/framework/Reflection/TypeProcessor.php on line 545
问题根因
报错由两个配置/代码问题共同触发:
- 消费者处理方法未显式声明入参类型
Magento消息队列组件会通过反射机制读取消费者处理方法的参数类型,做自动类型转换与合法性校验。当前消费者代码中process方法的$request参数没有声明类型,反射读取时返回null,传入要求string类型参数的resolveFullyQualifiedClassName方法时直接触发类型错误。 - 重复声明消费者handler
同时在communication.xml和queue_consumer.xml中定义了同一个topic对应的处理handler,Magento配置合并逻辑处理重复handler声明时会出现元数据读取异常,放大参数类型解析的问题。
修复步骤
- 第一步:修改消费者类代码,给
process方法的入参添加和communication.xml中request配置匹配的string类型声明:
<?php namespace TimoG\OrderTransfer\Model\Queue; use Exception; use Psr\Log\LoggerInterface; use Magento\Framework\Serialize\Serializer\Json; class Consumer { private $_logger; private Json $_json; public function __construct( LoggerInterface $logger, Json $json ) { $this->_json = $json; $this->_logger = $logger; } // 给$request添加string类型声明 public function process(string $request) { try { $test = $this->_json->unserialize($request); } catch (Exception $exc) { $this->_logger->critical($exc->getMessage()); } } }
- 第二步:删除
queue_consumer.xml中consumer节点的handler属性,只保留communication.xml中的handler定义即可,修改后的queue_consumer.xml如下:
<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework-message-queue:etc/consumer.xsd"> <consumer name="erp.queue.order" queue="erp.queue.order" connection="db"/> </config>
- 第三步:清理缓存与重新生成依赖配置,执行以下命令:
php bin/magento cache:clean config php bin/magento setup:di:compile
验证方式
重新执行消费者启动命令即可正常消费队列消息:
php bin/magento queue:consumers:start erp.queue.order
补充排查提示:如果修复后仍有同类报错,检查所有队列相关配置文件是否都放在模块的
etc/目录下,确认服务器上没有残留旧版本的配置文件,避免配置合并异常。
内容的提问来源于stack exchange,提问作者hallleron
相关产品推荐
相关产品推荐

