Setup / Getting started with Google Cloud PubSub using java client — Non Google App Engine deployment
Jul 21, 2017 · 3 min read
Setup google cloud account:
- Create google cloud account. Go to Console and create a new project.
- From the navigation drawer on left top, select API Manager Go to Dashboard and select Enable API and enable Google Pub/Sub api.
- Now Select Credentials option under API Manager. Select Create credentials drop down and select Service account key.
- Go to Service account drop down and click New service account.
- Enter Service account name, Select a Role (Pub/Sub -> Pub/Sub Admin, Editor, Publisher, Subscriber, Viewer), Service account ID auto-populates, which is customizable.
- Select Key type -> JSON (Recommended) and create which download a JSON file to your default downloads folder.
- From the navigation drawer, select Pub/Sub and verify if Pub/Sub is enabled.
Setup workspace:
- Now add a system environment variable in your environment as follows (For mac)
export GOOGLE_APPLICATION_CREDENTIALS=”/Users/{username}/Downloads/{downloaded_json_file}- Create a maven rest application and make below changes.
- 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();
}
}
}
PS, If you want Pub/Sub to send messages to subscribers, you first need to verify your server domain address in the google webmaster, I will cover this topic in future.
Some of the helpful resources and links :