Setup / Getting started with Google Cloud PubSub using java client — Non Google App Engine deployment

Dev app
Dev app
Jul 21, 2017 · 3 min read

Setup google cloud account:

  1. Create google cloud account. Go to Console and create a new project.
  2. From the navigation drawer on left top, select API Manager Go to Dashboard and select Enable API and enable Google Pub/Sub api.
  3. Now Select Credentials option under API Manager. Select Create credentials drop down and select Service account key.
  4. Go to Service account drop down and click New service account.
  5. Enter Service account name, Select a Role (Pub/Sub -> Pub/Sub Admin, Editor, Publisher, Subscriber, Viewer), Service account ID auto-populates, which is customizable.
  6. Select Key type -> JSON (Recommended) and create which download a JSON file to your default downloads folder.
  7. From the navigation drawer, select Pub/Sub and verify if Pub/Sub is enabled.

Setup workspace:

  1. Now add a system environment variable in your environment as follows (For mac)
export GOOGLE_APPLICATION_CREDENTIALS=”/Users/{username}/Downloads/{downloaded_json_file}
  1. Create a maven rest application and make below changes.
  2. Add below maven dependencies:
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-pubsub</artifactId>
<version>0.20.1-beta</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>22.0</version>
</dependency>
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-logging</artifactId>
<version>1.2.1</version>
</dependency>
<dependency>
<groupId>com.google.auth</groupId>
<artifactId>google-auth-library-oauth2-http</artifactId>
<version>0.7.1</version>
</dependency>
<dependency>
<groupId>com.google.oauth-client</groupId>
<artifactId>google-oauth-client</artifactId>
<version>1.22.0</version>
</dependency>

Code:

Creating a topic:

// Project_id from your json file
public static final String PROJECT_ID = "test-project-12345";
// Topic id you want to create and publish to
public static final String TOPIC_ID = "test-topic-1";
/**
* Create a new topic
*/
public static void createTopic() throws Exception {
TopicName topic = TopicName.create(PROJECT_ID, TOPIC_ID);
try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
topicAdminClient.createTopic(topic);
}
}

Publishing to a topic:

/**
* Publish to a topic
*/
public void publishMessageToATopic(Object messageData) throws Exception {
// Create TopicName object with which we create topic earlies
TopicName topicName = TopicName.create(PROJECT_ID, TOPIC_ID);

Publisher publisher = null;
List<ApiFuture<String>> messageIdFutures = new ArrayList<>();
try {
// Create a publisher instance with default settings.
// This will read the json file downloaded from the cloud account and
// authenticate our client
publisher = Publisher.defaultBuilder(topicName).build();
// Convert input messageData to json
ObjectMapper objectMapper = new ObjectMapper();
String jsonMessageString = objectMapper.writeValueAsString(messageData);

ByteString data = ByteString.copyFromUtf8(jsonMessageString);
PubsubMessage pubsubMessage = PubsubMessage.newBuilder().setData(data).build();
// After publishing the message, it will return a message id,
// which needs to be stored for future reference
ApiFuture<String> messageIdFuture = publisher.publish(pubsubMessage);
messageIdFutures.add(messageIdFuture);
} finally {
// wait on any pending publish requests.
List<String> messageIds = ApiFutures.allAsList(messageIdFutures).get();
for (String messageId : messageIds) {
log.info(" **** Message ID : " + messageId + " published **** ");
}
if (publisher != null) {
// When all the messages are published, free up resources.
publisher.shutdown();
}
}
}

)

Dev app

Written by

Dev app

Software Engineering, Programming, Travel, Food and Me.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade