NashTech Blog

Setting Up Google Cloud Project and Pub/Sub in Java

Table of Contents
imac turend on

Overview

Google Cloud Platform (GCP) provides robust services for building scalable and reliable cloud-based applications. One of these services is Google Cloud Pub/Sub, a messaging service that allows you to send and receive messages between independent applications.

In this blog post, we’ll walk you through the process of setting up a Google Cloud Project and using Google Cloud Pub/Sub in Java. We’ll cover the following steps:

  1. Creating a Google Cloud Project
  2. Enabling the Pub/Sub API
  3. Setting up Authentication
  4. Creating a Pub/Sub Topic and Subscription
  5. Writing Java Code to Publish and Consume Messages

Let’s get started!

1. Creating a Google Cloud Project

If you don’t have a Google Cloud account, sign up for one at Google Cloud Console. After signing in, create a new project. Give it a unique name and take note of the project ID, as you’ll need it later.

2. Enabling the Pub/Sub API

Once you have your project set up, enable the Google Cloud Pub/Sub API by following these steps:

  • Go to the Google Cloud Console.
  • Select your project from the dropdown in the upper-left corner.
  • Click on the “Navigation menu” (the three horizontal lines) and navigate to “APIs & Services” > “Dashboard.”
  • Click the “+ ENABLE APIS AND SERVICES” button.
  • Search for “Pub/Sub API” and click on it.
  • Click the “Enable” button.

3. Setting up Authentication

To access your Google Cloud resources programmatically, you’ll need to set up authentication. You can create a service account and download the JSON key file to authenticate your Java application.

  • In the Google Cloud Console, navigate to “IAM & Admin” > “Service accounts.”
  • Create a new service account, giving it a descriptive name and granting it the “Pub/Sub Editor” role.
  • After creating the service account, click on it, go to the “Keys” tab, and create a new key. Download the JSON key file and keep it safe.

4. Creating a Pub/Sub Topic and Subscription

In Google Cloud Pub/Sub, messages are published to topics, and subscribers consume messages from subscriptions to those topics. Let’s create a topic and a subscription:

  • Go to the Google Cloud Console and navigate to “Pub/Sub” > “Topics.”
  • Create a new topic and give it a name.
  • After creating the topic, navigate to the “Subscriptions” tab and create a new subscription connected to your topic.

5. Writing Java Code to Publish and Consume Messages

Now that you have your Google Cloud Project, Pub/Sub API enabled, and authentication set up, it’s time to write Java code to interact with Pub/Sub. You’ll need to add the Pub/Sub client library to your project’s dependencies.

Maven Dependency

<dependency>
    <groupId>com.google.cloud</groupId>
    <artifactId>google-cloud-pubsub</artifactId>
    <version>2.5.0</version> <!-- Use the latest version -->
</dependency>

Publish a Message

import com.google.api.core.ApiFuture;
import com.google.cloud.pubsub.v1.Publisher;
import com.google.protobuf.ByteString;
import com.google.pubsub.v1.PubsubMessage;
import com.google.pubsub.v1.TopicName;

public class PubSubPublisher {
    public static void main(String[] args) throws Exception {
        String projectId = "your-project-id";
        String topicId = "your-topic-id";

        TopicName topicName = TopicName.of(projectId, topicId);

        Publisher publisher = Publisher.newBuilder(topicName).build();

        String message = "Hello, Google Cloud Pub/Sub!";
        ByteString data = ByteString.copyFromUtf8(message);

        PubsubMessage pubsubMessage = PubsubMessage.newBuilder().setData(data).build();

        ApiFuture<String> future = publisher.publish(pubsubMessage);
        String messageId = future.get();
        System.out.println("Published message ID: " + messageId);

        publisher.shutdown();
    }
}

Consume Messages

import com.google.api.core.ApiService;
import com.google.cloud.pubsub.v1.*;

public class PubSubSubscriber {
    public static void main(String[] args) throws Exception {
        String projectId = "your-project-id";
        String subscriptionId = "your-subscription-id";

        SubscriptionName subscriptionName = SubscriptionName.of(projectId, subscriptionId);

        MessageReceiver receiver =
            (PubsubMessage message, AckReplyConsumer consumer) -> {
                System.out.println("Received message: " + message.getData().toStringUtf8());
                consumer.ack();
            };

        Subscriber subscriber = Subscriber.newBuilder(subscriptionName, receiver).build();
        subscriber.startAsync().awaitRunning();

        // Keep the program running to continue receiving messages
        subscriber.awaitTerminated();
    }
}

With this above code in place, you can publish and consume messages using Pub/Sub in your Java application.

Conclusion

In conclusion, Google Cloud Pub/Sub is a powerful messaging service that allows you to build distributed and scalable applications in the cloud. By following the steps outlined in this blog post, you can set up a Google Cloud Project and start using Pub/Sub in your Java applications to build robust and reliable message-based systems. I will be covering more topics on log4j in my future blogs, Stay connected. Happy learning 🙂

For more, you can refer to the Pub/Sub documentation: https://cloud.google.com/pubsub/docs/

For a more technical blog, you can refer to the Nashtech blog: https://blog.nashtechglobal.com/

Proudly powered by WordPress

Picture of Shivam Roy

Shivam Roy

I am working as a backend developer at Nashtech Global. I have worked on technologies like Java, spring boot, microservices, and MySql, Postman, GitHub, APIGEE (GCP), Webmethods. Apart from that my hobbies are playing guitar and listening to music.

Suggested Article

Scroll to Top