오늘의 인기 글
최근 글
최근 댓글
Today
Total
05-09 00:00
관리 메뉴

우노

[GCP] Pub/Sub Subscriber 메시지 수신 방법 with Python 본문

GCP/PubSub

[GCP] Pub/Sub Subscriber 메시지 수신 방법 with Python

운호(Noah) 2023. 8. 23. 17:05

들어가기 앞서,

  • Google Cloud Pub/Sub의 Subscriber는 두 가지 방식으로 메세지를 수신할 수 있습니다.
    • Subscribe (Push)
      • 구독자에게 메세지를 보내는 방식입니다.
    • Pull
      • 구독자가 필요할 때 메시지를 수동으로 가져오는 방식입니다.
  • 어떤 방식을 선택할지는 사용 사례와 요구 사항에 따라 다릅니다.
  • 실시간 데이터 처리가 필요한 경우에는 Subscribe(Push) 방식이 적합하며,
  • 일괄적인 처리나 비동기적인 작업이 가능한 경우에는 Pull 방식이 적합할 수 있습니다.

Subscribe 방식 예제 코드

from google.cloud import pubsub_v1
import json

def callback(message: pubsub_v1.subscriber.message.Message):
    data = json.loads(message.data.decode('UTF-8'))
    print("Received message:", data)

    # 메시지 처리 완료 알리기
    message.ack()

project_id = "your-project-id"
subscription_id = "your-subscription-id"
subscriber = pubsub_v1.SubscriberClient()
subscription_path = subscriber.subscription_path(project_id, subscription_id)
future = subscriber.subscribe(subscription_path, callback)

try:
    future.result(timeout=None)  # No timeout specified
except TimeoutError:
    print("Timeout error occurred.")
    future.cancel()
except KeyboardInterrupt:
    future.cancel()

Pull 방식 예제 코드

from google import pubsub_v1
import json

project_id = "your-project-id"
subscription_id = "your-subscription-id"
subscriber = pubsub_v1.SubscriberClient()
subscription_path = subscriber.subscription_path(project_id, subscription_id)

pull_request = pubsub_v1.PullRequest(subscription=subscription_path, max_messages=10000)
response = subscriber.pull(request=pull_request, timeout=300)

for received_message in response.received_messages:
    message_data = received_message.message.data.decode('utf-8')
    data = json.loads(message_data)
    print("Received message:", data)

    # 메시지 처리 완료 알리기
    subscriber.acknowledge(subscription=subscription_path, ack_ids=[received_message.ack_id])

'GCP > PubSub' 카테고리의 다른 글

[GCP] Pub/Sub Topic에 Message를 Publish 하는 방법 with Python  (0) 2024.03.07
Comments