/
RabbitQueue.php
126 lines (111 loc) · 3.3 KB
/
RabbitQueue.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
<?php
class RabbitQueue implements IQueue {
private $_conn;
private $_connInfo;
private $_exchange;
private $_queue;
function __construct($connInfo) {
if(empty($connInfo['routingKey'])){
$connInfo['routingKey'] = 'routingKey';
}
$connInfo['bindingkey'] = $connInfo['routingKey'];
if(empty($connInfo['exchangeName'])){
$connInfo['exchangeName'] = 'exchangeName';
}
if(empty($connInfo['queueName'])){
$connInfo['queueName'] = 'queueName';
}
$this->_connInfo = $connInfo;
}
public function open(){
if(empty($this->_connInfo)){
return false;
}
if($this->_conn){
return true;
}
$this->_conn = new AMQPConnection($this->_connInfo['connArgs']);
if (!$this->_conn->connect()) {
return false;
}
return true;
}
private function _initPublisher(){
if(!$this->open()){
return false;
}
if($this->_exchange){
return true;
}
$channel = new AMQPChannel($this->_conn);
//创建exchange
$this->_exchange = new AMQPExchange($channel);
$this->_exchange->setName($this->_connInfo['exchangeName']);
$this->_exchange->setType(AMQP_EX_TYPE_DIRECT);
$this->_exchange->setFlags(AMQP_DURABLE);
if(!$this->_exchange->declareExchange()) {
$this->close();
return false;
}
//创建队列,生产者和消费者都要创建队列
$queue = new AMQPQueue($channel);
$queue->setName($this->_connInfo['queueName']);
$queue->setFlags(AMQP_DURABLE);
$queue->declareQueue();
$queue->bind($this->_connInfo['exchangeName'],$this->_connInfo['routingKey']);
return true;
}
private function _initCustomer(){
if(!$this->open()){
return false;
}
if($this->_queue){
return true;
}
$channel = new AMQPChannel($this->_conn);
$this->_queue = new AMQPQueue($channel);
if(!$this->_queue){
$this->close();
return false;
}
$this->_queue->setName($this->_connInfo['queueName']);
$this->_queue->setFlags(AMQP_DURABLE);
$this->_queue->declareQueue();
$this->_queue->bind($this->_connInfo['exchangeName'],$this->_connInfo['bindingKey']);
return true;
}
public function close(){
if($this->_conn){
$this->_conn->disconnect();
$this->_conn = null;
}
}
public function push($message) {
if(!$this->open() || !$this->_initPublisher()){
return false;
}
return $this->_exchange->publish($message,$this->_connInfo['routingKey']);
}
public function pop() {
if(!$this->open() || !$this->_initCustomer()){
return false;
}
$messages = $this->_queue->get(AMQP_AUTOACK);
if(empty($messages)){
return false;
}
return $messages->getBody();
}
public function front() {
return false;
}
public function back() {
return false;
}
public function isEmpty() {
return true;
}
public function size() {
return -1;
}
}