写一个基类

  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. 如何解决 Nginx 端口映射到外网后访问地址端口丢失的问题

    1. 问题说明 一个手机h5页面的项目,使用nginx(监听80端口)进行访问,内网访问的地址是192.168.12.125/h5,访问正常,nginx中的配置如下: #微信H5页面访问 locati ...

  2. 对精致码农大佬的 [理解 volatile 关键字] 文章结论的思考和寻找真相

    一:背景 1. 讲故事 昨天在园里的编辑头条看到 精致码农大佬 写的一篇题为:[C#.NET 拾遗补漏]10:理解 volatile 关键字 (https://www.cnblogs.com/will ...

  3. 十八般武艺玩转GaussDB(DWS)性能调优(三):好味道表定义

    摘要:表结构设计是数据库建模的一个关键环节,表定义好坏直接决定了集群的有效容量以及业务查询性能,本文从产品架构.功能实现以及业务特征的角度阐述在GaussDB(DWS)的中表定义时需要关注的一些关键因 ...

  4. [Luogu P3626] [APIO2009] 会议中心

    题面 传送门:https://www.luogu.org/problemnew/show/P3626 Solution 如果题目只要求求出第一问,那这题显然就是大水题. 但是加上第二问的话...... ...

  5. Ordering Cows

    题意描述 好像找不到链接(找到了请联系作者谢谢),所以题目描述会十分详细: Problem 1: Ordering Cows [Bruce Merry, South African Computer ...

  6. 「SHOI2014」三叉神经树

    「SHOI2014」三叉神经树 给你一颗由\(n\)个非叶子结点和\(2n+1\)个叶子结点构成的完全三叉树,每个叶子结点有一个输出:\(0\)或\(1\),每个非叶子结点的输出为自己的叶子结点中较多 ...

  7. 【故障公告】Memcached 的“惹祸”,不知在为谁背锅

    在 .NET 5.0 背锅 . Memcached 的惹祸 .缓存雪崩之后,我们没有找到问题的真正原因,我们知道没有找到根源的故障总是会再次光临的,不是在这周就是在下周,也许就在双11前后. 就在今天 ...

  8. php执行exec、xsell_exec命令失败

    在php.ini下进行更改 查找disable_function 去掉exec xsell_exec 重启php

  9. C++ 中表达式求值

    首先我们来看一段代码: int a() { return std::puts("a"); } int b() { return std::puts("b"); ...

  10. java服务器部署开源项目(若依)

    1准备工作 (1)阿里云 centos_8_0_x64_20G_alibase_20200218.vhd [root@iZ2zeeqw5fxmm9zagf439aZ ~]# cat /etc/redh ...