This recipe shows you how to publish messages to a Cloud Pub/Sub topic from a Cloud Function.
View the source code.
-
Follow the Cloud Functions quickstart guide to setup Cloud Functions for your project.
-
Clone this repository:
git clone https://github.com/GoogleCloudPlatform/nodejs-docs-samples.git cd nodejs-docs-samples/functions/pubsub -
Create a Cloud Pub/Sub topic (if you already have one you want to use, you can skip this step):
gcloud alpha pubsub topics create [YOUR_TOPIC_NAME]- Replace
[YOUR_TOPIC_NAME]with the name of your Pub/Sub Topic.
- Replace
-
Create a Cloud Storage Bucket to stage our deployment:
gsutil mb gs://[YOUR_BUCKET_NAME]- Replace
[YOUR_BUCKET_NAME]with the name of your Cloud Storage Bucket.
- Replace
-
Deploy the
publishfunction with an HTTP trigger:gcloud alpha functions deploy publish --bucket [YOUR_BUCKET_NAME] --trigger-http- Replace
[YOUR_BUCKET_NAME]with the name of your Cloud Storage Bucket.
- Replace
-
Deploy the
subscribefunction with the Pub/Sub topic as a trigger:gcloud alpha functions deploy subscribe --bucket [YOUR_BUCKET_NAME] --trigger-topic [YOUR_TOPIC_NAME]- Replace
[YOUR_BUCKET_NAME]with the name of your Cloud Storage Bucket. - Replace
[YOUR_TOPIC_NAME]with the name of your Pub/Sub Topic.
- Replace
-
Call the
publishfunction:gcloud alpha functions call publish --data '{"topic":"[YOUR_TOPIC_NAME]","message":"Hello World!"}'- Replace
[YOUR_TOPIC_NAME]with the name of your Pub/Sub Topic.
- Replace
-
Check the logs for the
subscribefunction:gcloud alpha functions get-logs subscribeYou should see something like this in your console:
D ... User function triggered, starting execution I ... Hello World! D ... Execution took 1 ms, user function completed successfully