Introduction to Google Cloud Pub/Sub - Messaging Service
Introduction to Google Cloud Pub/Sub - Messaging Service
Google Cloud Pub/Sub is a fully managed messaging service that enables you to build event-driven systems and decouple applications for better scalability and reliability. In this guide, we'll explore the fundamentals of Google Cloud Pub/Sub and provide a sample Python code snippet for publishing and subscribing to Pub/Sub topics.
Key Concepts
Before we dive into the code, let's cover some key concepts related to Google Cloud Pub/Sub:
- Topics and Subscriptions: Messages are sent to topics, and subscribers receive messages from subscriptions to those topics.
- Publisher: A publisher sends messages to a topic. A publisher can be any application or service.
- Subscriber: A subscriber receives messages from a subscription. Subscribers can process messages, perform actions, or forward messages to other services.
Sample Code: Publishing and Subscribing to Pub/Sub
Here's a sample Python code snippet for publishing and subscribing to Google Cloud Pub/Sub topics:
Publishing to a Topic
from google.cloud import pubsub_v1 # Initialize the Publisher client publisher = pubsub_v1.PublisherClient() # Set your project ID and topic name project_id = 'your-project-id' topic_name = 'your-topic-name' # Create a topic path topic_path = publisher.topic_path(project_id, topic_name) # Define a message message_data = 'Hello, Pub/Sub!' message_data = message_data.encode('utf-8') # Publish the message future = publisher.publish(topic_path, data=message_data) print(f`Published message: {message_data}`)
Subscribing to a Topic
from google.cloud import pubsub_v1 # Initialize the Subscriber client subscriber = pubsub_v1.SubscriberClient() # Set your project ID, subscription name, and topic name project_id = 'your-project-id' subscription_name = 'your-subscription-name' topic_name = 'your-topic-name' # Create a subscription path subscription_path = subscriber.subscription_path(project_id, subscription_name) topic_path = subscriber.topic_path(project_id, topic_name) # Define a callback function to handle received messages def callback(message): print(f`Received message: {message.data}`) message.ack() # Subscribe to the topic and start receiving messages subscriber.subscribe(subscription_path, callback=callback) print(f`Subscribed to {subscription_name} for topic {topic_name}`) # Keep the script running to continue receiving messages import time while True: time.sleep(5)
Make sure to replace
your-project-id, your-topic-name, and other values with your specific project and configuration details.
Conclusion
Google Cloud Pub/Sub is a robust messaging service that allows you to build scalable and decoupled applications. By leveraging Pub/Sub, you can create event-driven systems and efficiently process messages within your cloud-based applications.