Pub/Sub API in Google Cloud Platform


The cloud Pub/Sub API is a traditional way to exchange messages between server and client. Pub/Sub is nothing but the publisher/subscriber model

The core concepts of pub/sub are

  1. ** Topic **: Topic is the main resource where messages get exchanged between publisher/subscriber

  2. ** Subscription**: Subscription is responsible to deliver messages from a single topic to the subscriber.

  3. ** Message **: Message is nothing but data that a publisher sends to a topic and it will be delivered to subscribers. This communication will happen through the topic.

Publisher-Subscription:

Relationship: A publisher will send messages to a topic. Subscriber will be subscribed to a topic where it will receive the message. We can send broadcasted messages like one to many or many to one or many to many.

** Message flow:**

  1. A publisher sends messages to the topic.

  2. Pub/Sub API is responsible for forwarding messages from a topic to all the subscribers.

  3. The subscriber receives pending messages from its topic which he is subscribed to.

  • Firstly we need to create a project in GCP and add pub/sub API to it.

  • If we want to use gcloud SDK we need to install it first in your system

    Here is the link to download it https://cloud.google.com/sdk/docs/downloads-apt-get

  • Command to create a topic in GCP is

gcloud pubsub topics create my-topic
  • Here is the command to subscribe to that topic
gcloud pubsub subscriptions create my-sub --topic my-topic

To publish a message:

Let us see an example to publish a message


const {PubSub} = require('@google-cloud/pubsub');


let pubsub = new PubSub();
// topic variable should be changed by topic which you created
 let topic = 'someTopicName';
 let pubData = JSON.stringify({ name: 'madhav' });

const dataBuffer = Buffer.from(data);

const id = await pubsub.topic(topic).publish(dataBuffer);
console.log(`Message ${id} published.`);

Receive message:

To receive the message we need to subscribe to a topic which is available in subscriptions.

let us see an example to receive a message

const {PubSub} = require('@google-cloud/pubsub');

const pubsub = new PubSub();


 const subscription = 'my-sub';
 const timeout = 60;


const subscription = pubsub.subscription(subName);

let count = 0;
const handler = message => {
  count += 1;
  message.ack();
};

subscription.on(`message`, handler);

setTimeout(() => {
  subscription.removeListener('message', handler);
  console.log(`${count} message(s) received.`);
}, timeout * 1000);