RabbitMq初探——php的一个demo
<?php /** * Created by PhpStorm. * Date: 2017/10/17 * Time: 16:21 */ class Rabbit { public function mq_set(){ $conn_args = [ 'host' => '127.0.0.1', //rabbitmq 服务器host 'port' => 5672, //rabbitmq 服务器端口 'login' => 'guest', //登录用户 'password' => 'guest', //登录密码 'vhost' => '/' //虚拟主机 ]; $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); } public function mq_produce(){ $conn_args = [ 'host' => '127.0.0.1', //rabbitmq 服务器host 'port' => 5672, //rabbitmq 服务器端口 'login' => 'guest', //登录用户 'password' => 'guest', //登录密码 'vhost' => '/' //虚拟主机 ]; $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); } public function mq_consume(){ $conn_args = [ 'host' => '127.0.0.1', 'port' => 5672, 'login' => 'guest', 'password' => 'guest', 'vhost' => '/' ]; $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'; } } $obj = new Rabbit(); $obj->mq_set(); $obj->mq_produce(); $obj->mq_consume();