· メッセージングと通信 · 2 min read
Cloud Pub/Sub でスケーラブルなメッセージングシステムを構築する
Google Cloud の Pub/Sub を使用して、高性能で信頼性の高いメッセージングシステムを構築する方法を解説します

Cloud Pub/Sub とは
Google Cloud Pub/Sub は、非同期メッセージングを実現するフルマネージドサービスです。publish-subscribe パターンを採用しており、アプリケーション間で効率的にデータを交換できます。
Pub/Sub の主要概念
- トピック: メッセージが公開される先
- サブスクリプション: トピックからメッセージを受信するためのエンドポイント
- メッセージ: トピックに公開されるデータ単位
Pub/Sub の利点
- スケーラビリティ: 毎秒数百万のメッセージを処理可能
- 信頼性: at-least-once デリバリーを保証
- 柔軟性: プッシュ型とプル型のサブスクリプションをサポート
Pub/Sub の実装手順
1. プロジェクトの設定
まず、Google Cloud プロジェクトを作成し、Pub/Sub API を有効にします。
2. トピックの作成
gcloud pubsub topics create my-topic
3. サブスクリプションの作成
gcloud pubsub subscriptions create my-sub --topic=my-topic
4. メッセージの公開
以下は Python を使用したメッセージ公開の例です:
from google.cloud import pubsub_v1
publisher = pubsub_v1.PublisherClient()
topic_path = publisher.topic_path(project_id, topic_id)
data = "Hello, Pub/Sub!"
future = publisher.publish(topic_path, data.encode("utf-8"))
print(f"Published message ID: {future.result()}")
5. メッセージの受信
サブスクライバーの実装例:
from google.cloud import pubsub_v1
subscriber = pubsub_v1.SubscriberClient()
subscription_path = subscriber.subscription_path(project_id, subscription_id)
def callback(message):
print(f"Received message: {message.data}")
message.ack()
streaming_pull_future = subscriber.subscribe(subscription_path, callback=callback)
print(f"Listening for messages on {subscription_path}")
try:
streaming_pull_future.result()
except KeyboardInterrupt:
streaming_pull_future.cancel()
Pub/Sub のユースケース
- イベント駆動型アーキテクチャ
- ストリーミングアナリティクス
- 非同期ワークフロー
- IoT データ処理
まとめ
Cloud Pub/Sub を使用することで、スケーラブルで信頼性の高いメッセージングシステムを簡単に構築できます。大規模なデータ処理や分散システムの構築に最適なソリューションです。
より詳細な情報や高度な使用方法については、以下の書籍がおすすめです:
徹底攻略 Google Cloud 認定資格 Associate Cloud Engineer 教科書
この書籍では、Pub/Sub を含む Google Cloud の主要サービスについて深く学ぶことができます