RabbitMQ Simple Queue
용어 정리
Hello World!
Sending
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
channel.queue_declare(queue='hello')
- channel를 통해 queue 선언(declare) 한다.
channel.basic_publish(exchange='',
routing_key='hello',
body='Hello World!')
print(" [x] Sent 'Hello World!'")
- channel의 publish(sending)을 한다.
- routing_key는 Queue 이름을 활용한다.
connection.close()
Receiving
channel.queue_declare(queue='hello')
- Sending이랑 동일하게 queue를 선언(declare)한다.
def callback(ch, method, properties, body):
print(" [x] Received %r" % body)
- Receiving 받을 함수 handler를 정의한다.
channel.basic_consume(callback,
queue='hello',
no_ack=True)
- Queue가 'hello'의 consuming 설정을 한다.
print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()
전체 코드
send.py
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()
channel.queue_declare(queue='hello')
channel.basic_publish(exchange='',
routing_key='hello',
body='Hello World!')
print(" [x] Sent 'Hello World!'")
connection.close()
receive.py
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()
channel.queue_declare(queue='hello')
def callback(ch, method, properties, body):
print(" [x] Received %r" % body)
channel.basic_consume(callback,
queue='hello',
no_ack=True)
print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()