GCP Pub/Sub는 Google Cloud의 완전 관리형 비동기 메시징 서비스로, 글로벌 규모의 이벤트 스트리밍과 서비스 디커플링을 지원한다. 초당 수백만 메시지를 처리할 수 있다.
Pub/Sub 핵심 개념
| 개념 | 설명 |
|---|
| Topic | 메시지 발행 채널 |
| Subscription | Pull 또는 Push 방식 구독 |
| Message | 데이터 + 속성 + 메시지 ID |
| Acknowledgement | 처리 완료 확인 (ack deadline 내) |
| Snapshot | 특정 시점 구독 상태 저장 |
python
from google.cloud import pubsub_v1
import json
project_id = "my-project"
topic_id = "order-events"
subscription_id = "order-processor"
# 발행
publisher = pubsub_v1.PublisherClient()
topic_path = publisher.topic_path(project_id, topic_id)
message = {
"orderId": "ORD-001",
"customerId": "CUST-123",
"amount": 99.99,
}
future = publisher.publish(
topic_path,
data=json.dumps(message).encode('utf-8'),
eventType="ORDER_PLACED",
region="ap-northeast1",
)
print(f"메시지 ID: {future.result()}")
# Pull 구독
subscriber = pubsub_v1.SubscriberClient()
subscription_path = subscriber.subscription_path(project_id, subscription_id)
def callback(message: pubsub_v1.types.PubsubMessage):
order = json.loads(message.data.decode('utf-8'))
try:
process_order(order)
message.ack()
except Exception as e:
message.nack()
streaming_pull_future = subscriber.subscribe(subscription_path, callback=callback)
streaming_pull_future.result(timeout=300)
bash
gcloud pubsub subscriptions create order-push-sub --topic=order-events --push-endpoint=https://my-service.run.app/pubsub/push --push-auth-service-account=pubsub-invoker@my-project.iam.gserviceaccount.com --ack-deadline=60
BigQuery 구독 (직접 적재)
bash
gcloud pubsub subscriptions create bq-sub --topic=order-events --bigquery-table=my-project:dataset.orders --use-topic-schema --write-metadata
Pub/Sub vs Kafka vs SQS
| 항목 | Pub/Sub | Kafka | SQS |
|---|
| 관리 | 완전 관리형 | 자체 관리 | 완전 관리형 |
| 메시지 보존 | 7일 | 설정 가능 | 최대 14일 |
| 글로벌 | 네이티브 | 복잡 | 리전별 |
| 정렬 보장 | 미지원 (기본) | 파티션 내 | FIFO만 |