root / logic / amqp_connection.py @ 5ad78098
History | View | Annotate | Download (1.2 kB)
1 |
import time |
---|---|
2 |
import socket |
3 |
from amqplib import client_0_8 as amqp |
4 |
from django.conf import settings |
5 |
|
6 |
_conn = None
|
7 |
_chan = None
|
8 |
|
9 |
def _connect(): |
10 |
global _conn, _chan
|
11 |
while _conn == None: |
12 |
try:
|
13 |
_conn = amqp.Connection(host=settings.RABBIT_HOST, |
14 |
userid=settings.RABBIT_USERNAME, |
15 |
password=settings.RABBIT_PASSWORD, |
16 |
virtual_host=settings.RABBIT_VHOST) |
17 |
except socket.error:
|
18 |
time.sleep(1)
|
19 |
_chan = _conn.channel() |
20 |
|
21 |
|
22 |
def send(payload, exchange, key): |
23 |
"""
|
24 |
Send payload to the specified exchange using the provided routing key
|
25 |
"""
|
26 |
global _conn, _chan
|
27 |
msg = amqp.Message(payload) |
28 |
msg.properties["delivery_mode"] = 2 # Persistent |
29 |
|
30 |
while True: |
31 |
try:
|
32 |
_chan.basic_publish(msg, |
33 |
exchange=exchange, |
34 |
routing_key=key) |
35 |
return
|
36 |
except socket.error:
|
37 |
#logger.exception("Server went away, reconnecting...")
|
38 |
_connect() |
39 |
except Exception as e: |
40 |
#self.logger.exception("Caught unexpected exception (msg: %s)", msg)
|
41 |
|
42 |
def __init__(): |
43 |
_connect() |