写一个基类

  1 <?php
2
3 namespace BI\Service\RabbitMQJob;
4
5 use AMQPConnection;
6 use AMQPChannel;
7 use AMQPExchange;
8 use AMQPQueue;
9 use Exception;
10
11 abstract class Base{
12
13 Const EXCHANGE_TYPE_DIRECCT = AMQP_EX_TYPE_DIRECT;
14 Const EXCHANGE_TYPE_FANOUT = AMQP_EX_TYPE_FANOUT;
15 Const EXCHANGE_TYPE_TOPIC = AMQP_EX_TYPE_TOPIC;
16
17 Const JOB_TYPE_MAIL = 'mail';
18 Const JOB_TYPE_TEST = 'test';
19 Const JOB_TYPE_STRUCTURE = 'structure';
20
21 /** @var AMQPChannel */
22 protected $channel;
23
24 /** @var AMQPExchange */
25 protected $exchange;
26
27 public function __construct($config, $vhost = '/')
28 {
29 extract($config);
30 $connArgs = array('host' => $host, 'port' => $port, 'login' => $login, 'password' => $password, 'vhost' => $vhost);
31
32 try {
33 $conn = new AMQPConnection($connArgs);
34 if (!$conn->connect()) {
35 throw new Exception('Cannot connect to the broker with parameters: ' . json_encode($connArgs));
36 }
37 $this->channel = new AMQPChannel($conn);
38 $this->declareExchange();
39 $this->bindQueues();
40 } catch (Exception $e) {
41 throw new Exception($e->getMessage());
42 }
43 }
44
45 protected function declareExchange(){
46 $this->exchange = new AMQPExchange($this->channel);
47 $this->exchange->setName($this->getExchangeName());
48 $this->exchange->setType($this->getExchangeType());
49 $this->exchange->setFlags(AMQP_DURABLE);
50 if(!$this->exchange->declareExchange())
51 throw new Exception('Exchange declare failed.');
52 }
53
54 protected function bindQueues(){
55 foreach($this->getQueueNamesAndRoutingKeys() as $queueName => $routingKey){
56 $queue = new AMQPQueue($this->channel);
57 $queue->setName($queueName);
58 $queue->setFlags(AMQP_DURABLE);
59 $queue->declareQueue();
60 if(!$queue->bind($this->getExchangeName(), $routingKey))
61 throw new Exception('Queue binding failed with parameters: ',
62 json_encode(array('name' => $queueName, 'routingKey' => $routingKey)));
63 }
64 }
65
66 /**
67 * @param mixed $content
68 * @param string $routingKey
69 * @return bool
70 * @throws Exception
71 */
72 protected function send($content, $routingKey = null){
73 if(!in_array($routingKey, $this->getQueueNamesAndRoutingKeys()))
74 throw new Exception('RoutingKey: ' . $routingKey
75 . ' is not found in the routing key list from the function getQueueNamesAndRoutingKeys');
76
77 $jobType = $this->getRabbitMQJobType();
78 if(!$this->validateJobType($jobType))
79 throw new Exception('Invalid Job Type.');
80
81 $message = array(
82 'MType' => $jobType,
83 'Content' => $content,
84 );
85 return $this->exchange->publish(json_encode($message), $routingKey);
86 }
87
88 protected function get($rk) {
89 if (!in_array($rk, $this->getQueueNamesAndRoutingKeys())) {
90 throw new Exception("RoutingKey: $rk is not found");
91 }
92 }
93
94 /**
95 * @param string $jobType
96 * @return bool
97 */
98 protected function validateJobType($jobType){
99 return in_array($jobType, array(
100 self::JOB_TYPE_MAIL,
101 self::JOB_TYPE_TEST,
102 self::JOB_TYPE_STRUCTURE,
103 ));
104 }
105
106 function __destruct(){
107 $this->channel->getConnection()->disconnect();
108 }
109
110
111 /**
112 * @return string
113 */
114 abstract protected function getRabbitMQJobType();
115
116 /**
117 * @return string
118 */
119 abstract protected function getExchangeName();
120
121 /**
122 * @return string
123 */
124 abstract protected function getExchangeType();
125
126
127 /**
128 * @return array queue_name => routing_key
129 */
130 abstract protected function getQueueNamesAndRoutingKeys();
131 }

写一个service继承基类

  1 <?php
2
3 namespace Mission\Service;
4 use BI\Service\RabbitMQJob\Base;
5 use Monolog\Handler\StreamHandler;
6 use Monolog\Logger;
7
8 class PublishToMQService extends Base
9 {
10 private $message;
11 private $logger;
12 private $error;
13 protected $queue = 'mission_queue';
14 protected $routingKey = 'api_update_mission';
15
16 /**
17 * @return bool
18 */
19 public function publish()
20 {
21 if ( false === $this->_validation() )
22 return false;
23
24 $this->getLogger()->addDebug(__METHOD__, array('MQMessage' => $this->message));
25 $this->sendToQueue($this->message, $this->queue);
26
27 return true;
28 }
29
30
31 /**
32 * @param array $message
33 * @return $this
34 */
35 public function setMessage( $message = array() )
36 {
37 $this->message = $message;
38
39 return $this;
40 }
41
42 /**
43 * @param $queue
44 * @return $this
45 */
46 public function setQueue( $queue )
47 {
48 $this->queue = $queue;
49
50 return $this;
51 }
52
53 /**
54 * @param $routingKey
55 * @return $this
56 */
57 public function setRoutingKey( $routingKey )
58 {
59 $this->routingKey = $routingKey;
60
61 return $this;
62 }
63
64 /**
65 * @return Logger
66 */
67 private function getLogger()
68 {
69 if (!($this->logger instanceof Logger)) {
70 $this->logger = new Logger('Detection');
71 $file = __DIR__ . DIRECTORY_SEPARATOR . '../../../logs/queue.log';
72 $this->logger->pushHandler(new StreamHandler( $file, Logger::DEBUG ));
73 }
74 return $this->logger;
75 }
76
77 /**
78 * @return bool
79 */
80 private function _validation()
81 {
82 if ( empty( $this->message ) ) {
83 $this->error = 'Message cannot be empty.';
84 return false;
85 }
86
87 return true;
88 }
89
90 /**
91 * @return string
92 */
93 protected function getExchangeName()
94 {
95 return 'API';
96 }
97
98 /**
99 * @return string
100 */
101 protected function getRabbitMQJobType()
102 {
103 return Base::JOB_TYPE_TEST;
104 }
105
106 /**
107 * @return string
108 */
109 protected function getExchangeType()
110 {
111 return parent::EXCHANGE_TYPE_DIRECCT;
112 }
113
114 /**
115 * @return array queue_name => routing_key
116 */
117 protected function getQueueNamesAndRoutingKeys()
118 {
119 return array(
120 $this->queue => $this->routingKey
121 );
122 }
123
124 private function sendToQueue($content, $queueName)
125 {
126 $key = $this->getQueueNamesAndRoutingKeys();
127 return parent::send($content, $key[$queueName]);
128 }
129
130 /**
131 * @return mixed
132 */
133 public function getError()
134 {
135 return $this->error;
136 }
137
138 }

在代码层调用service

 1 class AlarmController
2 {
3 const QUEUE = 'internal_message';
4 const ROUTING_KEY = 'api_internal_message';
5 public function checkTipAlarm()
6 {
7 //在线,写队列通知新站内信
8 /**@var PublishToMQService $publishHandler*/
9 $publishHandler = $this->get( 'mission.publish.RabbitMQ' );
10
11 $message = array(
12 'act' => self::ACT_SYSTEM_NEW_INMAIL,
13 'psid' => (is_numeric($this->request['to']) ? $this->request['to'] : ''),
14 'uuid' => (!is_numeric($this->request['to']) ? $this->request['to'] : ''),
15 'data' => array(
16 'owner' => $this->uuid
17 )
18 );
19
20 $publishHandler->setMessage( $message )->setRoutingKey( self::ROUTING_KEY )->setQueue( self::QUEUE );
21
22 if ( false === $publishHandler->publish() ) {
23 $this->error = array(
24 'errorMsg' => $publishHandler->getError(),
25 'errorCode' => 1
26 );
27 return false;
28 }
29 }
30 }

工作中使用RabbitMQ的更多相关文章

  1. 在Node.js中使用RabbitMQ系列二 任务队列

    在上一篇文章在Node.js中使用RabbitMQ系列一 Hello world我有使用一个任务队列,不过当时的场景是将消息发送给一个消费者,本篇文章我将讨论有多个消费者的场景. 其实,任务队列最核心 ...

  2. 浅谈surging服务引擎中的rabbitmq组件和容器化部署

    1.前言 上个星期完成了surging 的0.9.0.1 更新工作,此版本通过nuget下载引擎组件,下载后,无需通过代码build集成,引擎会通过Sidecar模式自动扫描装配异构组件来构建服务引擎 ...

  3. 二、消息队列之如何在C#中使用RabbitMQ

    1.什么是RabbitMQ.详见 http://www.rabbitmq.com/. 作用就是提高系统的并发性,将一些不需要及时响应客户端且占用较多资源的操作,放入队列,再由另外一个线程,去异步处理这 ...

  4. 二、消息队列之如何在C#中使用RabbitMQ(转载)

    二.消息队列之如何在C#中使用RabbitMQ 1.什么是RabbitMQ.详见 http://www.rabbitmq.com/. 作用就是提高系统的并发性,将一些不需要及时响应客户端且占用较多资源 ...

  5. python中的rabbitmq

    介绍 RabbitMQ是一个在AMQP基础上完整的,可复用的企业消息系统.他遵循Mozilla Public License开源协议.MQ全称为Message Queue, 消息队列(MQ)是一种应用 ...

  6. 在ABP core中使用RabbitMq

    距上一篇博客的更新一集很久了,主要是最近做的事情比较杂,中间也有一个难点,就是在ABP中加入APP扫码登录,本来想些的,但是觉得这个写出来会不会让我们的系统被破解-_-||,所以想了想,就没有写. 这 ...

  7. 简单介绍下怎么在spring中使用RabbitMQ

    这篇文章主要介绍了简单了解如何在spring中使用RabbitMQ,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 常见的消息中间件产品: (1)Ac ...

  8. .NET 环境中使用RabbitMQ

    在企业应用系统领域,会面对不同系统之间的通信.集成与整合,尤其当面临异构系统时,这种分布式的调用与通信变得越发重要.其次,系统中一般会有很多对实时性要求不高的但是执行起来比较较耗时的地方,比如发送短信 ...

  9. 随机记录工作中常见的sql用法错误(一)

    没事开始写博客,留下以前工作中常用的笔记,内容不全或者需要补充的可以留言,我只写我常用的. 网上很多类似动软生成器的小工具,这类工具虽然在表关系复杂的时候没什么软用,但是在一些简单的表结构关系还是很方 ...

随机推荐

  1. java 内存可见性

    java线程 -> 线程工作内存 -> 主物理内存 线程工作内存的原理是栈内是连续的小空间,寻址速度比堆快得多,将变量拷贝到栈内生成副本再操作 什么是重排序 代码指令可能并不是严格按照代码 ...

  2. java数据结构-10循环队列

    一.概念: 循环队列就是将队列存储空间的最后一个位置绕到第一个位置,形成逻辑上的环状空间,供队列循环使用 二.代码实现: @SuppressWarnings("unchecked" ...

  3. MySQL全面瓦解5:数据操作-DML

    说明 DML(Data Manipulation Language)数据操作语言,是指对数据库进行增删改的操作指令,主要有INSERT.UPDATE.DELETE三种,代表插入.更新与删除,这是学习M ...

  4. python数学math和random模块

    math模块 关注公众号"轻松学编程"了解更多. 在使用math模块时要先导入 # 导入模块 import math 1.math.ceil(num) 对num进行向上取整 num ...

  5. pycharm新建项目时选择virtualenv的说明

    虚拟环境及venv和virtualenv介绍:https://www.cnblogs.com/mind18/p/13877170.html pip介绍:https://www.cnblogs.com/ ...

  6. 微信小程序开发之云开发

    创建云开发小程序项目 开通云开发 开通后界面 选择开发环境 开启使用npm模块 安装wx-server-sdk npm install --save wx-server-sdk@latest 创建云函 ...

  7. php 导出excel 10万数据

    php导出excel 10万数据(此代码主要测试用) 在工作当中要对一些基本信息和其他信息导出 起初信息比较小无所谓.... 但当信息超出65535的时候 发现点问题了 超出了 而且 反应速度很慢 实 ...

  8. 【java】校验当前时间是否在规定的时间内

    废话不多说直接贴代码. 我的日期格式是 8:00-22:00 要用的自己换下格式哈. public class CheckClosingTimeUtil { /** * 校验当前时间是否在规定时间内 ...

  9. Docker - 解决重新进入容器后,环境变量失效的问题

    问题背景 在容器中,在 /etc/profile . /etc/environment 设置了环境变量 退出容器,重新进入容器 刚刚设置的环境变量失效了 解决办法 将环境变量设置在 /root/.ba ...

  10. full nat

    在餐馆吃饭时,连接无线网络后访问某网页会自动弹出一个认证页面,我想大家都经历过..... 其网络拓扑如下: sta-------------网络设备--------------公网 比如sta 终端i ...