How to create a simple messaging app using Google Cloud Pub Service?

Sandeep Pamidamarri
4 min readJul 24, 2021

--

In this particular post, we will learn to create a simple messaging app using Google Cloud Pub-Sub Service.

Pub-Sub is a simple messaging service — with a Publisher and Subscriber. The event-driven architecture breaks down the complexity of the application. Multiple subscribers can listen to the publisher's event through topics.

In this post, we will see a publisher python script to send a message and a subscriber python script to receive a message.

Pre-requisites

  1. Google Cloud Login
  2. VS Code

Step 1: Enable the Google Cloud Pub-Sub Service

Navigate to the https://console.cloud.google.com and enabled the Cloud Pub-Sub Service.

Click Enable

In Google Cloud console, click on the hamburger menu and select the Cloud Pub Sub service.

Step 2: Create a Topic to store the event messages

Topic is to store the event messages that the publishers sends.

Note: As part of the Topic creation, default subscription gets created

Verify the respective subscription details

Step 3: Create a Service Account to access the Pub Sub Service

In the IAM & Admin, navigate to the Service Accounts

Click on the Create Service Account

Provide the service account details.

Provide the PubSub Admin Role to the Service Account

Verify and click the created Service account

Generate a new JSON Key as below. This action will generate a JSON key file in the Downloads folder.

Step 4: Write Python Scripts to Publish and to Subscribe

Install following google-cloud-pubsub package using following command

pip install --upgrade google-cloud-pubsub

Create a Publisher.py file as below

import os;from google.cloud import pubsub_v1credentials_path = "PATH TO SECURITY KEY.json FILE"os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = credentials_pathpublisher = pubsub_v1.PublisherClient()topic_path = "projects/PROJECT_ID/topics/learning-pubsub-example1"data = "A message from a publisher"data = data.encode('utf-8')future = publisher.publish(topic_path, data)print("published message id", future.result())

After successful execution. Click on Topic and pull the messages in the topic.

Create a subscriber.py file as follows

import os;from google.cloud import pubsub_v1credentials_path = "PATH TO KEY.json"os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = credentials_pathtimeout = 5.0subscriber = pubsub_v1.SubscriberClient()subscription_path = "projects/PROJECT-ID/subscriptions/learning-pubsub-example1-sub"def callback(message):print('Received message:', message)print('data: ',message.data)message.ack()streaming_pull_future = subscriber.subscribe(subscription_path, callback=callback)print("Listening for messages on ", subscription_path)with subscriber:try:# streaming_pull_future.result(timeout = timeout)streaming_pull_future.result()except TimeoutError:streaming_pull_future.cancel()streaming_pull_future.result()

Step 5: Testing the changes

Open the two terminals

In one terminal, execute the publisher.py using the following command

python publisher.py

In other terminals execute the subscriber.py using the following command

python subscriber.py\

You can observe the publisher and respective subscriber executions simultaneously.

You can pass the JSON data in the publisher using the attributes variable.

data = "A message from a publisher"data = data.encode('utf-8')attributes = {"customer_id": "432432","first_name" :"John","last_name" :"Carter"}future = publisher.publish(topic_path, data, **attributes)print("published message id", future.result())

Note: Delete the service account, topic and disable pub-sub service in the cloud developer console.

Wohooooooo, Congratulations :) — Now you successfully learned how to use the Google Cloud PubSub event messaging service.

--

--

Sandeep Pamidamarri
Sandeep Pamidamarri

Written by Sandeep Pamidamarri

Digital Transformation Leader | Pega Lead Solution Architect | Pega Certified Data Scientist | Pega Customer Service | Pega Sales Automation | AWS Cloud

No responses yet