google-cloud-platformpublish-subscribepullreplysubscriber

Reply a message after receiving data on subscriber in Google PubSub Pull


Is it possible to reply a message once you received a data from Publisher. It must be a direct reply, once the Publisher published a message. I'm using Google PubSub Service.

https://cloud.google.com/pubsub/docs/pull

Publisher/Sender (PHP):

$sendToOps =[];
$sendToOps['MESSAGE'] = "my message";
$topicName = env('GOOGLE_CLOUD_TO_OPS_TOPIC');

$pubSub = new PubSubClient();
$topic = $pubSub->topic($topicName);
$ret =  $topic->publish([
          'attributes'=>$sendToOps
       ]);

//**********The word "Apple" must output here**********
echo $ret;
//*****************************************************

Subscriber/Receiver (Javascript):

'use strict';


//Get .env File Data
require('dotenv').config({path: '/usr/share/nginx/html/myProject/.env'});
var request = require('request');

var port = process.env.PORT_GATEWAY;
var host = process.env.IP_PUSH;
var test = process.env.TEST_FLAG;
var pubsubSubscription = process.env.GOOGLE_CLOUD_TO_OPS_SUBSCRIPTION;
const keyFilePath= 'public/key/key.json';

// Imports the Google Cloud client library
const {PubSub} = require('@google-cloud/pubsub');

// Creates a client; cache this for further use
const pubSubClient = new PubSub({
  keyFilename: keyFilePath
});

function listenForMessages() {
  // References an existing subscription
  const subscription = pubSubClient.subscription(pubsubSubscription);

  // Create an event handler to handle messages
  const messageHandler = message => {
  console.log(message.attributes);


   //*****************************************************
   //I want to reply to Sender with the word "Apple" here
   //*****************************************************


   message.ack()
  };
   
  subscription.on('message', messageHandler);
}

  listenForMessages();



Solution

  • Is it possible to reply a message once you received a data from Publisher.

    Depends on what you mean by "reply". The publisher of a message posts a message on a Pub/Sub Topic. Subscribers receive messages from a Pub/Sub Subscription. There is no two-way communications channel here. There is no Pub/Sub reply back method.

    A subscriber could publish a message to a different topic that the publisher reads as a subscriber. Both sides would be publisher and a subscriber but on different topics.

    Once a message is received, a subscriber could directly call an API on the publisher.

    However, the intent of Publish/Subscribe is to decouple senders from receivers and not to lock them together.