php操作rabbitmq
1.配置交换机,队列,然后绑定
<?php
$conn_args = [
'host' => '127.0.0.1', //rabbitmq 服务器host
'port' => 5672, //rabbitmq 服务器端口
'login' => 'demo', //登录用户
'password' => '123456', //登录密码
'vhost' => 'demo' //虚拟主机
];
$config = [
'exchangeName' => 'wochacha_duiba',
'eqeueName' => 'wochacha_duiba',
'routeName' => 'duiba',
];
$e_name = $config['exchangeName'];
$q_name = $config['eqeueName'];
$k_route = $config['routeName'];
$conn = new AMQPConnection($conn_args);
$connect = $conn->connect();
if (!$connect) {
die('Cannot connect to the broker');
}
$channel = new AMQPChannel($conn);
// 创建交换机
$ex = new AMQPExchange($channel);
$ex->setName($e_name);
$ex->setType(AMQP_EX_TYPE_DIRECT); // 设置路由规则
$ex->setFlags(AMQP_DURABLE | AMQP_AUTODELETE); // 这个要创建的交换机是否持久化
$ex->declareExchange(); // 执行创建, 不要用declare(), 已经过时了,会报错的
// 创建队列
$q = new AMQPQueue($channel);
$q->setName($q_name);
$q->setFlags(AMQP_DURABLE | AMQP_AUTODELETE); // 同上
$q->declareQueue(); // 同上
$q->bind($e_name, $k_route);
2.生产者
<?php
$conn_args = [
'host' => '127.0.0.1', //rabbitmq 服务器host
'port' => 5672, //rabbitmq 服务器端口
'login' => 'demo', //登录用户
'password' => '123456', //登录密码
'vhost' => 'demo' //虚拟主机
];
$config = [
'exchangeName' => 'wochacha_duiba',
'routeName' => 'duiba',
];
$e_name = $config['exchangeName'];
$k_route = $config['routeName'];
$conn = new AMQPConnection($conn_args);
$connect = $conn->connect();
if (!$connect) {
die('Cannot connect to the broker');
}
$channel = new AMQPChannel($conn);
$ex = new AMQPExchange($channel);
$ex->setName($e_name);
$msg = '123';
$ex->publish($msg, $k_route);
3. 消费者
$conn_args = [
'host' => '192.168.73.128',
'port' => 5672,
'login' => 'demo',
'password' => '123456',
'vhost' => 'demo'
];
$config = [
'eqeueName' => 'wochacha_duiba',
];
$q_name = $config['eqeueName'];
$conn = new AMQPConnection($conn_args);
if (!$conn->connect()) {
die('Cannot connect to the broker');
}
$channel = new AMQPChannel($conn);
$q = new AMQPQueue($channel);
$q->setName($q_name);
$arr = $q->get();
if (!$arr) return;
$ack = $arr->getDeliveryTag();
$res = $q->ack($ack);
$msg = $arr->getBody();
echo $msg . "\n";
return 'ok';
note: 一般是这样操作的,运维把$conn_args配好,运行一次脚本1, 然后生产中执行脚本2,3来生产和消费。