1
1
#encoding=utf-8
2
2
import time
3
+ import uuid
3
4
import logging
4
5
import requests
5
6
import pika
@@ -48,6 +49,12 @@ def __init__(self,
48
49
def __getattribute__ (self , attr ):
49
50
"""每次使用connection,channel的时候都要检查一下是否已经断开连接了
50
51
"""
52
+ try :
53
+ create_kk = object .__getattribute__ (self , "create_kk" )
54
+ except AttributeError :
55
+ create_kk = 0
56
+ if create_kk :
57
+ return object .__getattribute__ (self , attr )
51
58
if attr in ("connection" , "channel" ):
52
59
try :
53
60
connection = object .__getattribute__ (self , "connection" )
@@ -56,13 +63,30 @@ def __getattribute__(self, attr):
56
63
try :
57
64
connection .process_data_events ()
58
65
except (StreamLostError , ChannelWrongStateError , ValueError , TypeError ):
59
- logging .debug ("队列连接已断开或发生错误!" )
66
+ logging .info ("队列连接已断开或发生错误!" )
60
67
if connection .is_closed or channel .is_closed :
61
68
new_con = pika .BlockingConnection (connect_params )
62
69
new_chan = new_con .channel ()
63
70
object .__setattr__ (self , "connection" , new_con )
64
71
object .__setattr__ (self , "channel" , new_chan )
65
- logging .debug ("重新连接了队列!" )
72
+ logging .info ("重新连接了队列!" )
73
+ except AttributeError :
74
+ pass
75
+ elif attr in ("send_connection" , "send_channel" ):
76
+ try :
77
+ send_connection = object .__getattribute__ (self , "send_connection" )
78
+ send_channel = object .__getattribute__ (self , "send_channel" )
79
+ connect_params = object .__getattribute__ (self , "connect_params" )
80
+ try :
81
+ send_connection .process_data_events ()
82
+ except (StreamLostError , ChannelWrongStateError , ValueError , TypeError ):
83
+ logging .info ("发送队列连接已断开或发生错误!" )
84
+ if send_connection .is_closed or send_channel .is_closed :
85
+ new_send_con = pika .BlockingConnection (connect_params )
86
+ new_send_channel = new_send_con .channel (channel_number = 9 )
87
+ object .__setattr__ (self , "send_connection" , new_send_con )
88
+ object .__setattr__ (self , "send_channel" , new_send_channel )
89
+ logging .info ("重新连接了发送队列!" )
66
90
except AttributeError :
67
91
pass
68
92
return object .__getattribute__ (self , attr )
@@ -71,8 +95,12 @@ def __exit__(self, exc_type, exc_val, exc_tb):
71
95
self .close_connection ()
72
96
73
97
def create_connection (self ):
98
+ self .create_kk = 1
74
99
self .connection = pika .BlockingConnection (self .connect_params )
75
100
self .channel = self .connection .channel ()
101
+ self .send_connection = pika .BlockingConnection (self .connect_params )
102
+ self .send_channel = self .send_connection .channel (channel_number = 9 )
103
+ self .create_kk = 0
76
104
77
105
def getConnectionParam (self ,
78
106
host ,
@@ -103,8 +131,32 @@ def getConnectionParam(self,
103
131
params ['port' ] = port
104
132
return pika .ConnectionParameters (** params )
105
133
134
+ def reconnect_queue_if_close (func ):
135
+ """如果连接断了,重连一下
136
+ """
137
+
138
+ def ware (self , * args , ** kwargs ):
139
+ try :
140
+ self .connection .process_data_events ()
141
+ except (StreamLostError , ChannelWrongStateError , ValueError ):
142
+ logging .debug ("队列连接已断开或发生错误!" )
143
+ pass
144
+
145
+ if self .connection .is_closed or self .channel .is_closed :
146
+ logging .debug ("重新连接了队列!" )
147
+ self .create_connection ()
148
+
149
+ return func (self , * args , ** kwargs )
150
+
151
+ return ware
152
+
106
153
def close_connection (self ):
107
- self .connection .close ()
154
+ self .create_kk = 1
155
+ if not self .send_connection .is_closed :
156
+ self .send_connection .close ()
157
+ if not self .connection .is_closed :
158
+ self .connection .close ()
159
+ self .create_kk = 0
108
160
109
161
def declare_exchange (self , exchange , ** kwargs ):
110
162
exchange_type = kwargs .get ('exchange_type' , 'direct' )
@@ -129,6 +181,10 @@ def declare_delay_exchange(self, exchange, **kwargs):
129
181
exchange = exchange , exchange_type = 'x-delayed-message' , durable = durable , arguments = arguments )
130
182
except ChannelClosedByBroker as e :
131
183
logging .warning (e )
184
+ self .create_kk = 1
185
+ self .connection .close ()
186
+ self .send_connection .close ()
187
+ self .create_kk = 0
132
188
self .create_connection ()
133
189
self .channel .exchange_declare (
134
190
exchange = exchange , exchange_type = exchange_type , durable = durable , arguments = arguments )
@@ -156,9 +212,11 @@ def declare_queue(self, queue, **kwargs):
156
212
def delete_queue (self , queue ):
157
213
self .channel .queue_delete (queue = queue )
158
214
215
+ # @reconnect_queue_if_close
159
216
def bind_exchange_queue (self , queue , exchange , binding_key = __default_routing_key ):
160
217
self .channel .queue_bind (queue = queue , exchange = exchange , routing_key = binding_key )
161
218
219
+ # @reconnect_queue_if_close
162
220
def send (self , message , exchange , routing_key , ** kwargs ):
163
221
"""
164
222
kwargs 参数说明:
@@ -167,7 +225,7 @@ def send(self, message, exchange, routing_key, **kwargs):
167
225
priority是消息优先级
168
226
expiration是消息生存周期,与delay相冲突,如果使用了expiration,delay就无效了
169
227
"""
170
- message_id = kwargs .get ('message_id' )
228
+ message_id = kwargs .get ('message_id' ) or str ( uuid . uuid4 ())
171
229
expiration = kwargs .get ('expiration' )
172
230
close_connection = kwargs .get ('close_connection' , False )
173
231
priority = kwargs .get ('priority' , 0 )
@@ -185,30 +243,34 @@ def send(self, message, exchange, routing_key, **kwargs):
185
243
headers = self .arg_set ('x-delay' , delay , headers )
186
244
187
245
property_params = self .arg_set ('headers' , headers , property_params )
188
- self .channel .basic_publish (
246
+ self .send_channel .basic_publish (
189
247
exchange = exchange ,
190
248
routing_key = routing_key ,
191
249
body = message ,
192
250
properties = pika .BasicProperties (** property_params ))
193
251
if close_connection :
194
252
self .close_connection ()
195
253
254
+ # @reconnect_queue_if_close
196
255
def consume (self , queue , auto_ack = False , inactivity_timeout = None , prefetch_count = None ):
197
256
if prefetch_count :
198
257
self .channel .basic_qos (prefetch_count = prefetch_count )
199
258
result = self .channel .consume (queue , auto_ack , inactivity_timeout = inactivity_timeout )
200
259
for nn in result :
201
260
yield nn
202
261
262
+ # @reconnect_queue_if_close
203
263
def run (self ):
204
264
try :
205
265
self .channel .start_consuming ()
206
266
finally :
207
267
self .channel .stop_consuming ()
208
268
self .close_connection ()
209
269
270
+ # @reconnect_queue_if_close
210
271
def ack_message (self , method ):
211
- self .channel .basic_ack (delivery_tag = method .delivery_tag )
272
+ return self .channel .basic_ack (delivery_tag = method .delivery_tag )
212
273
274
+ # @reconnect_queue_if_close
213
275
def rej_message (self , method , requeue = False ):
214
- self .channel .basic_reject (delivery_tag = method .delivery_tag , requeue = requeue )
276
+ return self .channel .basic_reject (delivery_tag = method .delivery_tag , requeue = requeue )
0 commit comments