백엔드 Back-end/메시지 큐 Message Queue

Q. 파이썬으로 래빗엠큐RabbitMQ 메시지를 보내고 받고 싶다면?

Tap to restart 2023. 3. 6. 01:00
반응형

A. pika 팩키지를 활용하면 된다.

RabbitMQ 공식 홈페이지에 pika 튜토리얼이 있다. 튜토리얼 그대로 따라하면 쉽게 테스트를 해볼 수 있다.

 

도커로 RabbitMQ 실행하기

/Users/taptorestart 부분은 여러분의 경로로 수정하면 된다.
참고: rabbitmq dockerhub

docker run --name rabbitmq \
	-p 5672:5672 \
	-p 15672:15672 \
	-v /Users/taptorestart/rabbitmq:/var/lib/rabbitmq \
	-d rabbitmq:3.11.10-management

이 때 중요한 것은 -p 5672:5672도 적어줘야 한다는 점이다.

실행했으면 접속하자.
http://localhost:15672/ 로 접속하고 id, password는 guest, guest이다.

깃허브 rabbitmq-tutorials에 들어가면 각 언어별 예제 코드가 있다.

파이썬의 경우 pika란 팩키지를 활용한다. pip install pika로 설치부터 하자.

 

send.py

아래 코드를 그대로 복사해서 send.py로 저장하자. 

출처: rabbitmq-tutorials, Apache-2.0 license

#!/usr/bin/env python
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()

python send.py로 실행하자.

아래처럼 메시지가 추가된 것을 확인할 수 있다.

Queues 메뉴를 눌러서 들어가보면 hello란 이름의 큐가 생긴 것을 볼 수 있다.

receive.py

이번에는 메시지를 받는 코드인 receive.py를 추가하자.

#!/usr/bin/env python
import pika, sys, os

def main():
    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(queue='hello', on_message_callback=callback, auto_ack=True)

    print(' [*] Waiting for messages. To exit press CTRL+C')
    channel.start_consuming()

if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        print('Interrupted')
        try:
            sys.exit(0)
        except SystemExit:
            os._exit(0)

출처: rabbitmq-tutorials, Apache-2.0 license

 

실행해보면 메시지를 받는 것을 확인할 수 있다. 

그리고 메시지가 사라진 것을 볼 수 있다.

 

반응형