Magento2如何使用rabbitmq
备注:帮助初学者如何在M2中使用rabbitmq,避免小白初学者哗哗的掉头发。所以本作者写一篇详细的使用教程。
在evn.php文件中添加:
'amqp' => [
'host' => '127.0.0.1',
'port' => '5672',
'user' => 'guest',
'password' => 'guest',
'virtualhost' => '/',
'ssl' => false
]
在自己项目的etc文件中创建communication.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Communication/etc/communication.xsd">
<topic name="customer.clean" request="string" response="string" />
</config>
name:主题名称。
request:主题类型
在自己项目的etc文件中创建queue_topology.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework-message-queue:etc/topology.xsd">
<exchange name="am.customer.delete" type="topic" connection="amqp">
<binding id="AmCustomerClean" topic="customer.clean" destinationType="queue"
destination="customer_clean"/>
</exchange>
</config>
queue_topology.xml中主要是用于在rabbitmq中创建交换机和队列
name 交换机名
type 交换机类型
connection:链接类型,amqp是就是rabbitmq db就是数据库
id:唯一
topic:主题名
destinationType="queue"固定写法,别问为什么
destination:队列名
在自己项目的etc文件中创建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="AmCustomerClean" queue="customer_clean" connection="amqp"
consumerInstance="Magento\Framework\MessageQueue\BatchConsumer"
handler="Amasty\QExample\Model\Customer\DeleteConsumer::processMessage" />
</config>
消费者
name 消费者名字
queue 队列名
connection上面说过了
handler指定的处理方法
创建完成后跑命令:php bin/magento setup:upgrade (在哪跑命令你肯定知道,如果连这个命令都不知道在哪跑,那你可能要先去学M2的基础了)
创建的交换机和队列已经展示在你的界面上了;(界面从哪来?百度搜rabbitmq教程)
php bin/magento queue:consumers:list
可以看到我们刚刚创建的消费者已经出来了。
运行该命令
php bin/magento queue:consumers:start AmCustomerClean
Not found merger for consumer name ‘AmCustomerClean’
在项目的model中创建Merger.php
<?php
namespace Amasty\QExample\Model;
use Magento\Framework\MessageQueue\MergerInterface;
class Merger implements MergerInterface
{
public function merge(array $messages)
{
return $messages;
}
}
问题完美解决。
测试:
哎呀,咋有报错了,提示 Property ‘message_id’ not found in properties.
经研究代码发现,原来手动直接在rabbitmq的队列中添加没有message_id这个值,所以这个地方一定要用magento2入队方法。
$this->publisher->publish('customer.clean', json_encode([1=>'sssss']));
//customer.clean 队列名
完美解决。