- 消费者
<?php
$config = [
'host' => '172.17.0.7',
'vhost' => 'my_vhost',
'port' => '5672',
'login' => 'admin',
'password' => 'admin'
];
$conn = new AMQPConnection($config);
if (!$conn->connect()) {
exit('连接失败');
}
$chanel = new AMQPChannel($conn);
$exchange = new AMQPExchange($chanel);
$routingKey = 'key';
$exchangeName = 'exchange';
$exchange->setName($exchangeName);
$exchange->setType(AMQP_EX_TYPE_DIRECT);
$exchange->setFlags(AMQP_DURABLE);
$exchange->declareExchange();
$queue = new AMQPQueue($chanel);
$queue->setName('queue');
$queue->setFlags(AMQP_DURABLE);
$queue->declareQueue();
$queue->bind($exchange->getName(), $routingKey);
$queue->consume('receive');
function receive($envelope, $queue) {
sleep(2);
echo $envelope->getBody() . '\n';
$queue->ack($envelope->getDeliveryTag());
}
- 生产者
<?php
$config = [
'host' => '172.17.0.7',
'vhost' => 'my_vhost', // 虚拟机
'port' => '5672',
'login' => 'admin',
'password' => 'admin'
];
$conn = new AMQPConnection($config);
if (!$conn->connect()) {
exit('连接失败');
}
// 创建信道
$chanel = new AMQPChannel($conn);
// 创建交换机
$exchange = new AMQPExchange($chanel);
$routingKey = 'key';
$exchangeName = 'exchange';
// 设置交换机名称
$exchange->setName($exchangeName);
// 设置交换机类型
$exchange->setType(AMQP_EX_TYPE_DIRECT);
$exchange->setFlags(AMQP_DURABLE);
// 申明交换机
$exchange->declareExchange();
// 创建10个消息
for ($i = 0; $i < 10; $i++) {
$msg = array(
'data' => 'message'.$i,
);
// 发送消息到交换机并返回结果
// elivery_mode:2 声明消息持久
// 持久的队列 + 持久的消息
// 在RabbitMQ重启后才不会丢失
echo "Send Message:".$exchange->publish(json_encode($msg), $routingKey, AMQP_NOPARAM, array('delivery_mode' => 2)) . "\n";
}