1、生产者
public function push() {
try {
$conf = [
'host' => '127.0.0.1',
'port' => 5672,
'user' => 'admin',
'pwd' => 'admin',
'vhost' => '/',
];
$exchangeName = 'kd_sms_send_ex'; //交换机名
$queueName = 'green_queue'; //队列名称
$routingKey = 'green'; //路由关键字(也可以省略)
//建立生产者与mq之间的连接
$conn = new AMQPStreamConnection($conf['host'], $conf['port'], $conf['user'], $conf['pwd'], $conf['vhost']);
$channel = $conn->channel(); //在已连接基础上建立生产者与mq之间的通道
$channel->exchange_declare($exchangeName, 'direct', false, true, false); //声明初始化交换机
$channel->queue_declare($queueName, false, true, false, false); //声明初始化一条队列
$channel->queue_bind($queueName, $exchangeName, $routingKey); //将队列与某个交换机进行绑定,并使用路由关键字
$msgBody = json_encode([
"name" => "Test",
"age" => 22
]);
$msg = new AMQPMessage($msgBody, [
'content_type' => 'text/plain',
'delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT
]); //生成消息
$r = $channel->basic_publish($msg, $exchangeName, $routingKey); //推送消息到某个交换机
$channel->close();
$conn->close();
} catch (Exception $e) {
var_dump($e);
die;
}
}
2、消费者
public function test() {
$conf = [
'host' => '127.0.0.1',
'port' => 5672,
'user' => 'admin',
'pwd' => 'admin',
'vhost' => '/',
];
$exchangeName = 'kd_sms_send_ex'; //交换机名
$queueName = 'green_queue'; //队列名称
$routingKey = 'green'; //路由关键字(也可以省略)
//建立生产者与mq之间的连接
$conn = new AMQPStreamConnection($conf['host'], $conf['port'], $conf['user'], $conf['pwd'], $conf['vhost']);
$channel = $conn->channel(); //在已连接基础上建立生产者与mq之间的通道
$channel->exchange_declare($exchangeName, 'direct', false, true, false); //声明初始化交换机
$channel->queue_declare($queueName, false, true, false, false); //声明初始化一条队列
$channel->queue_bind($queueName, $exchangeName, $routingKey); //将队列与某个交换机进行绑定,并使用路由关键字
echo ' [*] Waiting for messages. To exit press CTRL+C', "\n";
$callback = function ($msg) {
echo " [x] Received ", $msg->body, "\n";
echo " [x] Done", "\n";
$msg->delivery_info['channel']->basic_ack($msg->delivery_info['delivery_tag']);
};
$channel->basic_qos(null, 1, null);
$channel->basic_consume($queueName, '', false, false, false, false, $callback);
while (count($channel->callbacks)) {
$channel->wait();
}
$channel->close();
$conn->close();
}