☁️ Cloud Functions – Cloud Pub/Sub Trigger
Google Cloud Functions integrates seamlessly with Cloud Pub/Sub to execute code whenever a message is published to a topic. This allows for event-driven architectures where functions react to data streams in real time. 🚀
✅ Step-01: Introduction
We’ll create:
- A Cloud Pub/Sub Topic
- A Cloud Function triggered by Pub/Sub Events
✅ Step-02: Create Cloud Pub/Sub Topic
Navigate to Cloud Pub/Sub → CREATE TOPIC
Enter the following details:
- Topic ID: mytopic1
- Leave the rest of the settings as default
Click CREATE
Review your setup:
- Check that the Topic was created
- Verify the Subscription is attached
✅ Step-03: Create Cloud Function with Pub/Sub Trigger
Configuration Tab
- Service name: cf-demo2-events-pubsub
- Region: us-central1
- Trigger: Cloud Pub/Sub
- Topic: mytopic1
- More Options → Review defaults
- Click NEXT
Code Tab
- Runtime: Node.js 20
- Use the auto-populated sample code (below)
- Click Save and DEPLOY
const functions = require('@google-cloud/functions-framework');
// Register a CloudEvent callback with the Functions Framework that will
// be executed when the Pub/Sub trigger topic receives a message.
functions.cloudEvent('helloPubSub', cloudEvent => {
// The Pub/Sub message is passed as the CloudEvent's data payload.
const base64name = cloudEvent.data.message.data;
const name = base64name
? Buffer.from(base64name, 'base64').toString()
: 'World';
console.log(`Hello, ${name}!`);
});
✅ Step-04: Review Cloud Function Logs
- Navigate to: Cloud Function → cf-demo2-events-pubsub → Logs
- You’ll see execution logs once messages are published.
✅ Step-05: Publish Messages to the Topic
Go to Cloud Pub/Sub → mytopic1 → MESSAGES → PUBLISH MESSAGE
Enter:
- Number of Messages: 10
- Message Body: My Pub/Message
Click PUBLISH
✅ Step-06: Review Logs Again
- Go to Cloud Function Logs
- You should see:
Hello, My Pub/Message!
logged multiple times (once for each published message)
Top comments (0)