一、首先安装好RabbitMQ
二、添加PHP amqp扩展,不然无法使用
三、直接上代码
生产者:
<?php
class Producer
{
private $config = [
'host' => 'localhost',//换成自己的地址
'port' => '5672',
'vhost' => '/',
'login' => 'admin',
'password' => 'admin'
];
private $exchangeName;//要和消费者的一致
private $routKey;//要和消费者的一致
public function __construct($exchangeName, $routKey = null)
{
$this->exchangeName = $exchangeName;
$this->routKey = $routKey;
}
public function send()
{
//模拟数据
$message = json_encode(['id' => mt_rand()]);
$connection = new \AMQPConnection($this->config);
try {
if(!$connection->connect()){
throw new \Exception('连接失败');
}
//创建Channel
$channel = new \AMQPChannel($connection);
//设置交换机
$exchange = new \AMQPExchange($channel);
$exchange->setName($this->exchangeName);
//设置类型
$exchange->setType(\AMQP_EX_TYPE_DIRECT);
//交换器持久化
// $exchange->setFlags(\AMQP_DURABLE);
$exchange->declareExchange();
//publish发送消息
//delivery_mode=>2 消息持久化,可以和队列持久化一起保证消息不丢失
if($exchange->publish($message, $this->routKey, \AMQP_NOPARAM,['delivery_mode' => 2])){
echo '发送成功';
}else{
throw new \Exception('发送失败:'.$message);
}
} catch (\Exception $e) {
echo $e->getMessage();
}
$connection->disconnect();// 断开连接
}
}
(new Producer('hua','test'))->send();
消费者
<?php
class Customer
{
private $config = [
'host' => 'localhost',//换成自己的地址
'port' => '5672',
'vhost' => '/',
'login' => 'admin',
'password' => 'admin'
];
private $exchangeName;
private $routKey;
private $queueName;
public function __construct($queueName,$exchangeName,$routKey = null)
{
$this->exchangeName=$exchangeName;
$this->routKey=$routKey;
$this->queueName=$queueName;
}
public function start()
{
$conn = new \AMQPConnection($this->config);
try {
if (!$conn->connect()) {
throw new \Exception('未连接');
}
$channel = new \AMQPChannel($conn);
//设置每次只能处理一条
$channel->qos(0,1);
//创建队列
$q = new \AMQPQueue($channel);
$q->setName($this->queueName);
$q->setFlags(\AMQP_DURABLE);
$q->declareQueue();
//将给定的队列绑定到交换机上
$q->bind($this->exchangeName,$this->routKey);
while(True){
//消费
$q->consume(function($envelope, $queue) {
$msg = $envelope->getBody();
sleep(2);
echo $msg . PHP_EOL;
$queue->ack($envelope->getDeliveryTag()); //手动发送ACK应答
});
}
}catch (\Exception $e){
echo $e->getMessage();
$conn->disconnect();
}
}
}
(new Customer('huahua','hua','test'))->start();
效果展示