RabbitMQ 에 Publish/Subscribe 하는 방식입니다.
Publish
topic 으로 호출하는 방식
import pika
import json
class Publish(object):
def __init__(self):
self.connection = None
self.channel = None
self.topic = None
def is_connect(self, host, topic=None):
try:
self.topic = topic
self.connection = pika.BlockingConnection(pika.ConnectionParameters(
host=host
))
self.channel = self.connection.channel()
self.channel.queue_declare(queue=self.topic, durable=True)
return True
except ConnectionError:
return False
def on_publish(self, message):
self.channel.basic_publish(exchange='amq.topic',
routing_key='',
body=json.dumps(message),
properties=pika.BasicProperties(
delivery_mode=2,
))
print('[x] Sent %r' % message)
self.connection.close()
def publish(host, topic, message, routing_key=''):
import pika
import json
connection = pika.BlockingConnection(
pika.ConnectionParameters(host=host))
channel = connection.channel()
channel.queue_declare(queue=topic, durable=True)
# message = {'id': 1, 'name': 'name1'}
channel.basic_publish(exchange='amq.topic',
routing_key=routing_key,
body=json.dumps(message),
properties=pika.BasicProperties(
delivery_mode=2, # make message persistent
))
print(" [x] Sent %r" % message)
connection.close()
# if __name__ == '__main__':
# 함수 호출 방식
# publish('localhost', 'my/topic', "{'id': 1, 'name': 'name1'}")
# 클래스 호출 방식
# tmp = Publish()
# if tmp.on_connect('localhost', 'my/topic'):# tmp.on_publish("{'id': 1, 'name': 'name1'}")
'Python' 카테고리의 다른 글
[Python] Private PYPI (0) | 2016.11.09 |
---|---|
[Python3] two list for loop (0) | 2016.11.08 |
[Python] 파이썬 정규식 (0) | 2016.10.27 |
[Python] call by assignment (call by object, call by object reference) (0) | 2016.10.26 |
[Python] SQL Injection 과 보호 방법 (0) | 2016.10.13 |
댓글