본문 바로가기
Python

[Python] RabbitMQ Publish Subscribe

by 혀나Lee 2016. 10. 26.

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'}")






댓글