개인 저장용 블로그

RabbitMQ Tutorials - Hello Wolrd (3) 본문

오픈소스/RabbitMQ

RabbitMQ Tutorials - Hello Wolrd (3)

우엉잇 2022. 4. 4. 10:16
이번 목차는 메시지 큐를 단순하게 보내고 받을 수 있는 내용입니다. 

 사용 가능한 언어로는 Python, Java Ruby, PHP, C#, JavaScript, Go, Elixir, Objective-C, Swift, Spring AMQP 있지만, Python 으로 진행 할 예정입니다. 

동작방식 (출처 : RabbitMQ 홈페이지)

 

1.2.1.1.  Python

 

- Python 소스 코드 작성

 

Send.py

#!/usr/bin/env python
import pika
 
# RabbitMQ Server 연결
# 다른 시스템에 연결 하려면 localhost 부분에 IP 주소 입력
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
 
# Message Queue 생성
channel.queue_declare(queue='hello')
 
# RabbitMQ Message Queue 직접 보낼 없으며 항상 exchange 거쳐야
channel.basic_publish(exchange='',
                      routing_key='hello',
                      body='Hello World!')
print(" [x] Sent 'Hello World!'")
 
# 연결닫기
connection.close()

 

Recevice.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)

 

- Message Queue테스트

 

# message queue 받을 준비

 

root@master:/product/python# python3 recevice.py

[*] Waiting for messages. To exit press CTRL+C
 

 

위의 py 파일을 실행 종료 하지 않는다.

 

# message queue 보내기

root@master:/product/python# python3 send.py

[x] Sent 'Hello World!'

 

# 받은 message queue  확인하기

root@master:/product/python# python3 recevice.py

 

[*] Waiting for messages. To exit press CTRL+C
 [x] Received b'Hello World!'

 

Recevice 에서 ‘Hello World!’ 라는 queue 받는 것을 확인 있다.

 

 - RabbitMQ Console 확인 

Rabbit Console queue 확인

 

‘queue’ 태그를 확인 보면 overview hello라는 queue 확인 있다.