[RabbitMQ] Fast API 서비스와 RabbitMQ 통신 테스트

목적

  • Fast API 서비스 하나를 생성한 후, 특정 Rest API Execute 명령이 실행 되면 RabbitMQ Queue 에 메시지 저장 되는지 테스트 진행합니다.

RabbitMQ Manager Docker Container 실행

  • 먼저 RabbitMQ Manager 이미지를 다운받아 Container 로 실행 시킵니다.
  • Docker 실행 명령어는 다음과 같습니다.
 docker run -d --hostname rabbitManage --name rabbitManage -p 30000:15672 rabbitmq:3-management

Fast API, uvicorn, pika 모듈 설치

  • 다음으로는 Fast API, ucivron, pika 3개의 모듈들을 설치 진행합니다.
  • 설치 명령어는 아래와 같습니다.
pip install fastapi
pip install uvicorn
pip install piak
  • 위 3개의 모듈들이 설치 되어 있어야, Fast API 서비스 작성 및 RabbitMQ 통신 코드를 작성할 수 있습니다.

Fast API 서비스 코드 작성

  • 환경 설정은 모두 마쳤습니다.
  • 다음으로, Fast API 서비스 코드를 작성해 보도록 하겠습니다.
  • Fast API 코드에는 RabbiiMQ 와 Connect 하여 MessageQueue 로 메시지를 Publisher 하는 내용이 들어 있습니다.
  • 일종의 Send 역할을 한다고 생각하면 됩니다.
import uvicorn
import pika

from fastapi import FastAPI

app = FastAPI()

# RabbitMQ 연결
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost', 
                                                               heartbeat=600, 
                                                               blocked_connection_timeout=300))
channel = connection.channel()

@app.get("/")
def root():
    a = "a"
    b = "b" + a

    channel.queue_declare(queue=b)

    channel.basic_publish(exchange='',
                      routing_key='hello',
                      body='Hello World!')
    print(" [x] Sent 'Hello World!'")

    return {"hello world": b}


if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)

Receive 코드 작성

  • 앞서 Fast API 서비스가 실행 되면, Swagger UI 를 통해 executer 를 할 때 마다 메시지가 RabbitMQ Queue 에 저장 됩니다.
  • 실제로 저장된 메시지를 다시 꺼내와서 해당 내용을 출력하는 reveive.py 파일을 작성 하였습니다.
import pika

connection = pika.BlockingConnection(pika.ConnectionParameters('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',
                      auto_ack=True,
                      on_message_callback=callback)

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

Fast API 서비스 실행

  • 먼저 Fast API 서비스를 실행 합니다.
  • localhost:8000 에 접속하게 되면, 실행이 정상적으로 되는 것을 확인할 수 있습니다.
  • 실제로 receive 를 실행하여 RabbitMQ Queue 의 메시지를 receive 가 가져와서 출력하는지 확인합니다.


Receive 서비스 실행

  • 실행 결과, 앞서 Fast API 가 보내서 RabbitMQ Queue 에 저장했던 Hello World! 메지시를 Receive 에서 가져와서 정상적으로 출력 되는 것을 확인할 수 있습니다.
(rabbitmq) C:\venvs\rabbitmq>python receive.py
 [*] Waiting for messages. To exit press CTRL+C
 [x] Received b'Hello World!'
 [x] Received b'Hello World!'
728x90

이 글을 공유하기

댓글

Designed by JB FACTORY