(1).config.php 配置文件<?php
/**
* RabbitMQ_Config
*/
$config = [
'host' => '127.0.0.1',
'port' => '5672',
'login' => 'guest',
'password' => 'guest',
'vhost' => '/'
];
(2).producer.php 生产者文件<?php
//加载配置文件
require './config.php';
global $config;
//设置交换机和路由Key
$ename = 'e_linvo';
$rname = 'r_router';
//实例化AMQP(必须手动connect)
$conn = new AMQPConnection($config);
if ($conn->connect() == false)
{
die('Cannot connect...');
}
//创建Channel(),Why?Who?
//如果每次访问MQ都建立一个连接,在量大的时候建立TCP开销巨大,Channel是在connection内部建立的逻辑连接
$channel = new AMQPChannel($conn);
//创建交换机并设置交换机名称
$exChange = new AMQPExchange($channel);
$exChange->setName($ename);
//通过交换机发送消息
$message = [
'userid' => 1024,
'username' => 'php',
];
$message = json_encode($message);
$exChange->publish($message, $rname);
echo '投递队列成功
';
(3).consumer.php 消费者文件<?php
//加载配置文件
require './config.php';
global $config;
//设置交换机和路由Key和队列key
$ename = 'e_linvo';
$rname = 'r_router';
$qname = 'q_queler';
//实例化AMQP(必须手动connect)
$conn = new AMQPConnection($config);
if ($conn->connect() == false)
{
die('Cannot connect...');
}
//创建Channel(),Why?Who?
//如果每次访问MQ都建立一个连接,在量大的时候建立TCP开销巨大,Channel是在connection内部建立的逻辑连接
$channel = new AMQPChannel($conn);
//创建交换机并设置交换机名称、交换数据类型、持久化
$exChange = new AMQPExchange($channel);
$exChange->setName($ename);
$exChange->setType(AMQP_EX_TYPE_DIRECT);
$exChange->setFlags(AMQP_DURABLE);
$exChange->declareExchange();
//创建队列,设置队列名称,并设置持久化
$queue = new AMQPQueue($channel);
$queue->setName($qname);
$queue->setFlags(AMQP_DURABLE);
$queue->declareQueue();
//将队列和交换机和路由进行绑定
$queue->bind($ename, $rname);
//Cli阻塞接收消息队列
while (true)
{
$queue->consume(function ($envelope, $queue) {
//获取队列的数据
$data = $envelope->getBody();//队列数据
$data = json_decode($data);
//处理数据
if ($data)
{
//todo
var_dump($data);
}
//手动Ack应答.确认收到信息.队列会删除本条
$queue->ack($envelope->getDeliveryTag());
});
}