介绍
RabbitMQ是一个在AMQP基础上实现的企业级消息系统。何谓消息系统,就是消息队列系统,消息队列是“”消费-生产者模型“”的一个典型的代表,一端往消息队列中不断写入消息,而另一端则可以读取或者订阅队列中的消息。
在项目中,将一些无需即时返回且耗时的操作提取出来,进行了异步操作,而这种异步处理的方式大大的节省了服务器的请求时间,从而提高了系统的吞吐量。而且不影响服务器做其他相应,不独占服务器资源。
如:注册用户这种服务,它可能解耦成好几种独立的服务(账号验证,邮箱验证码,手机短信码等)。它们作为消费者,等待用户输入数据,在前台数据提交之后会经过分解并发送到各个服务所在的url,分发的那个角色就相当于生产者。消费者在获取数据时候有可能一次不能处理完,那么它们各自有一个请求队列,那就是内存缓冲区了。做这项工作的框架叫做消息队列。
又比如:电商系统中的订单处理系统,传统处理模式是:下订单的时候,订单系统可能会调用库存系统的接口,这样两个系统之间存在一个严重依赖关系,如果库存系统宕机,那么整个流程都会受到影响。现在大多公司的处理方法是:引入消息队列,下完订单,订单系统完成持久化处理,将消息写入消息队列,返回用户订单下单成功。
对库存系统来说,采用拉/推的方式,获取下单信息,库存系统根据下单信息,进行库存操作。这样实现了两个系统间的解耦。
即使在下单时库存系统不能正常使用。也不影响正常下单,因为下单后,订单系统写入消息队列就不再关心其他的后续操作了。
结构图如下:
Exchange:消息交换机,它指定消息按什么规则,路由到哪个队列。
Queue:消息队列载体,每个消息都会被投入到一个或多个队列。
Binding:绑定,它的作用就是把exchange和queue按照路由规则绑定起来。
Routing Key:路由关键字,exchange根据这个关键字进行消息投递。
vhost:虚拟主机,一个broker里可以开设多个vhost,用作不同用户的权限分离。
producer:消息生产者,就是投递消息的程序。
consumer:消息消费者,就是接受消息的程序。
channel:消息通道,在客户端的每个连接里,可建立多个channel,每个channel代表一个会话任务。
(2)客户端声明一个exchange,并设置相关属性。
(3)客户端声明一个queue,并设置相关属性。
(4)客户端使用routing key,在exchange和queue之间建立好绑定关系。
(5)客户端投递消息到exchange。
(1)exchange持久化,在声明时指定durable => 1
(2)queue持久化,在声明时指定durable => 1
(3)消息持久化,在投递时指定delivery_mode => 2(1是非持久化)
好了,讲了这么多基本讲清楚了RabbitMQ的应用场景和好处,下面我们在windows平台上练一把手,更直观的来看看RabbitMQ到底是什么?
安装就省了,网上有很多教程,在此不做过多赘述。
类封装
定义一个名为 rabbitmq.php的类文件
<?php class RabbitMQ { private $connect;//连接对象 private $channel;// private $exchange;//交换机对象 private $exchange_name;//交换机名称 private $exchange_type;//交换机类型 private $queue;//对列对象 private $queue_name;//队列名称 private $queue_type;//对列类型 private $call_back_fnc;//回调函数 private $is_ack;//是否确认收到消息 public function __construct($params=[], $persistent_flag=false) { try { $con['host'] = $params['host'] ?? '127.0.0.1'; $con['vhost'] = $params['vhost'] ?? '/'; $con['port'] = $params['port'] ?? 5672; $con['login'] = $params['login'] ?? 'guest'; $con['password'] = $params['password'] ?? 'guest'; $this -> exchange_name = $params['exchange_name'] ?? ''; $this -> exchange_type = $params['exchange_type'] ?? AMQP_EX_TYPE_DIRECT; $this -> queue_name = $params['queue_name'] ?? ''; $this -> queue_type = $params['queue_type'] ?? AMQP_EX_TYPE_DIRECT; //连接初始化 $this -> connect = $this -> connectInit($con, $persistent_flag); if(!$con) { throw new Exception('Cannot connect to the broker!'); } $this -> channel = new AMQPChannel($this -> connect); } catch(Exception $ex) { $error_msg = "Exception error connect: {$ex->getMessage()}, line: {$ex->getLine()} "; writeLog('msg:'. $error_msg); return false; } } /** * 连接初始化 * @param $config array 配置信息 * @param persistent_flag bool 持久化 * @return object */ public function connectInit($config, $persistent_flag) { $connect = new AMQPConnection($config); if (!$connect->pconnect()) { return false; } if($persistent_flag) { $connect->isPersistent(1); } return $connect; } /** * 设置交换机 * @param $params['exchange_name'] string 交换机名称 * @param $params['exchange_type'] string 交换机类型 * @param $params['flag'] int 交换机标志 * @return object | bool */ public function setExchange($params) { $error_msg = ''; try{ if(!$this->channel){ throw new AMQPQueueException("Error channel on method setExchange", 1); } $this->exchange = new AMQPExchange($this->channel); if($params['exchange_name']){ $this->exchange_name = $params['exchange_name']; // 交换机名称 } if (empty($this->exchange_name)) return false; $this->exchange->setName($this->exchange_name); // 设置名称 if($params['exchange_type']){ $this->exchange_type = $params['exchange_type']; } $this->exchange->settype($this->exchange_type); // 设置交换机类型 if($params['flag']){ $this->exchange->setFlags($params['flag']); //交换机标志 } if($this -> exchange_type && $params['flag']){ $this->exchange->declareExchange(); // 创建 } } catch(AMQPQueueException $ex) { $error_msg = "AMQPQueueException error exchange: {$ex->getMessage()}, line: {$ex->getLine()} "; } catch(Exception $ex) { $error_msg = "Exception error exchange: {$ex->getMessage()}, line: {$ex->getLine()} "; } if($error_msg){ writeLog($error_msg); return false; } return $this; } /** * 设置队列 * @param $params['queue_name'] string 对列名称 * @param $params['flag'] int 对列标记 * @param $params['arguments'] array 参数配置 * @param $params['routing_key'] string 要绑定的模式或路由键 * @return object | bool */ public function setQueue($params){ $error_msg = ''; try{ $this->queue = new AMQPQueue($this->channel); if (!empty($params['exchange_name'])) { $this -> exchange_name = $params['exchange_name']; } if(!empty($params['queue_name'])) { $this->queue_name = $params['queue_name']; // 队列名称 } $this->queue->setName($this->queue_name); if($params['flag']){ $this->queue->setFlags($params['flag']); // 队列标志。与消息持久化有关。 这篇文字不涉及这一块的说明 } if(is_array($params['arguments']) && !empty($params['arguments'])){ $this->queue->setArguments($params['arguments']); // 参数配置 } $this->queue->declareQueue(); // 创建一个队列 $routing_key = !empty($params['routing_key']) ? $params['routing_key'] : $this->queue_name; if($this -> exchange_name && $routing_key){ $this->queue->bind($this ->exchange_name, $routing_key); // 交换机和队列的绑定操作 } } catch(AMQPQueueException $ex) { $error_msg = "AMQPQueueException error queue: {$ex->getMessage()}, line: {$ex->getLine()} "; } catch(Exception $ex) { $error_msg = "Exception error queue: {$ex->getMessage()}, line: {$ex->getLine()} "; } if($error_msg){ writeLog($error_msg); return false; } return $this; } /** * 发布消息 * @param $params['message'] string 消息 * @param $params['routing_key'] string 要绑定的模式或路由键 * @param $params['flag'] int 参数配置 AMQP_NOPARAM | AMQP_IMMEDIATE * @param $params['attributes'] array * @return bool */ public function publishMessage($params=[]){ if(!$params['message']) return false; $routing_key = $params['routing_key'] ? $params['routing_key'] : $this->queue_name; $params['attributes'] = $params['attributes'] ?? []; // 发布消息,带有路由key。如果需要,则会用于关联。 $this->exchange->publish($params['message'], $routing_key, $params['flag'], $params['attributes']); return true; } /** * 消费 * @param $params['callback'] arguments 回调函数 * @param $params['qos'] int 要预取的消息数 * @param $params['is_ack'] bool 是否确认收到消息 */ public function consumeMessage($params){ $params['callback'] = $params['callback'] ?? null; $params['qos'] = $params['qos'] ?? 0; $params['is_ack'] = $params['is_ack'] ?? true; if($params['qos']){ $this->channel->qos(0, $params['qos']); } $error_msg = ''; try{ if(!$this->queue){ throw new AMQPQueueException("Error queue on method consume", 1); } $this->call_back_fnc = $params['callback']; $this->is_ack = $params['is_ack']; $params['callback'] = function($envelope, $queue){ if(is_callable($this->call_back_fnc)){ call_user_func($this->call_back_fnc, $envelope->getBody()); if($this->is_ack){ $queue->ack($envelope->getDeliveryTag()); }else{ $queue->nack($envelope->getDeliveryTag()); } } }; $this->queue->consume($params['callback']); } catch(AMQPQueueException $ex) { $error_msg = "AMQPQueueException error queue: {$ex->getMessage()}, line: {$ex->getLine()} "; } catch(Exception $ex) { $error_msg = "Exception error queue: {$ex->getMessage()}, line: {$ex->getLine()} "; } if($error_msg){ writeLog($error_msg); } } } function writeLog($msg){ $logFile = './rabbitmq_w_' . date('N') . '.log'; $fp = fopen($logFile,"a"); $requestdir = dirname($logFile); if (!is_dir($requestdir)) { mkdir($requestdir, 0777, 1); } flock($fp, LOCK_EX); fwrite($fp,date("Y-m-d H:i:s",time()).": ".$msg." "); flock($fp, LOCK_UN); fclose($fp); }
生产消息
定义一个名称为sender.php的文件
<?php require_once './rabbitmq.php'; $config = [ 'host' => '127.0.0.1', //IP地址 'vhost' => '/', //主机 'port' => 5672, //端口号 'login' => 'guest', //用户名 'password' => 'guest', //密码 ]; $mq = new RabbitMQ($config); // 初始化(rmq连接操作); if ($mq) { $mq_route = 'push_data_to_routing'; // 路由 $mq_exchange = 'push_data_to_exchange'; // 交换机 $mq_queue = 'push_data_to_queue'; // 队列 // 建立连接,设置交换机,设置队列 $exchange_params = [ 'exchange_name' => $mq_exchange, 'exchange_type' => AMQP_EX_TYPE_DIRECT, 'flag' => AMQP_DURABLE, ]; $queue_params = [ 'queue_name' => $mq_queue, 'exchange_name' => $mq_exchange, 'routing_key' => $mq_route, 'flag' => AMQP_DURABLE, ]; $publish_params = [ 'routing_key' => $mq_route, ]; $data_list = ['iphone','honor','vivo','xiaomi','oppo']; $mq->setExchange($exchange_params)->setQueue($queue_params); foreach ($data_list as $item){ $publish_params['message'] = $item; $mq->publishMessage($publish_params); //推送 } }
接收消息
定义一个名称为receiver.php的文件
<?php require_once './rabbitmq.php'; $config = [ 'host' => '127.0.0.1', //IP地址 'vhost' => '/', //主机 'port' => 5672, //端口号 'login' => 'guest', //用户名 'password' => 'guest', //密码 ]; $mq = new RabbitMQ($config); $mq_route = 'push_data_to_routing'; $mq_exchange = 'push_data_to_exchange'; $mq_queue = 'push_data_to_queue'; $exchange_params = [ 'exchange_name' => $mq_exchange, 'exchange_type' => '', 'flag' => AMQP_PASSIVE, ]; $queue_params = [ 'queue_name' => $mq_queue, 'flag' => AMQP_PASSIVE, ]; $mq->setExchange($exchange_params)->setQueue($queue_params); $mq->consumeMessage([ 'callback'=>function($msg){ sleep(2); var_dump($msg); return true; } ]);
执行
win+R 调出cmd,切换至代码所在目录,一个窗口执行sender.php 一个窗口执行receiver.php
结果如下: