Message pubish in goolge cloud pubsub topic with java client
Table Of Contents
- What is Pub/Sub?
- What are the benefits of using Pub/Sub?
- Core concepts of Pub/sub.
- How to publish a message in pub/sub topic in java with credentials?
- Shutdown publisher when application stop or no need publisher.
- GitHub project link of reusable module.
- How to publish and receive a message in pub/sub in cloud console?
- Conclusion.
What is Pub/Sub?
Cloud Pub/Sub is a fully-managed messaging service provided by Google Cloud Platform. It is designed to provide reliable, scalable, and real-time messaging between applications and services.
Cloud Pub/Sub allows you to publish and consume messages from any application or service, regardless of the language or platform they are built on. It provides a simple and flexible architecture that decouples your systems and allows them to work independently.
In Cloud Pub/Sub, you can create one or more topics to which you can publish messages. Subscribers can then subscribe to the topic and receive all published messages in real-time. Cloud Pub/Sub guarantees the delivery of each message at least once, ensuring that every message is received by at least one subscriber.
Cloud Pub/Sub provides many features, including filtering and delivery control, which allow you to control which messages are delivered to which subscribers, as well as rate-limiting and message retention policies to help you manage your data. Additionally, Cloud Pub/Sub integrates with many other services in the Google Cloud Platform, making it easy to build complex applications and workflows.
What are the benefits of using Pub/Sub?
-Easily scale your message processing
-Decouple your message producers from your message consumers
-Guarantee delivery of messages by using Google’s global infrastructure
-Monitor the health of your message processing system with built-in metrics and logs
Pub/Sub is a flexible, reliable, and cost-effective way to process large volumes of messages. it is extremely efficient at moving data between databases and in storage. A large queue of tasks can be easily distributed among multiple devices for the most balanced workload. And because Pub/Sub decouples your message producers from your message consumers, you can add or remove consumers without affecting your producers.
Core concepts of Pub/sub
- Topic: A named resource to which messages are sent by publishers.
- Subscription: In order to get the data published on the topic, we must subscribe to that topic. Subscription represents the streaming message from a unique topic to be delivered to the subscribing application.
- Message: A data that is going to be published and subscribed.
- Message attribute: Depending on the receiver’s language, the publisher can define a key-value pair for the message.
- Publisher: An application that creates and sends messages to single or multiple topics.
- Subscriber: An application with a subscription to single or multiple topics to receive messages from it.
- Push and pull: The two message delivery methods. A subscriber receives messages either by Pub/Sub pushing them to the subscriber-chosen endpoint or by the subscriber pulling them from the service.
How to publish a message in pub/sub topic in java with credentials?
To publish a message to a Google Cloud Pub/Sub topic using Java with credentials, follow these steps:
- Ensure that you have created a Google Cloud project, enabled the Cloud Pub/Sub API, and created a topic.
- Add the Google Cloud Pub/Sub client library to your Java project. You can do this by adding the following dependency to your project's pom.xml file if you are using Maven:
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-pubsub</artifactId>
<version>1.123.2</version>
</dependency>
- In your Java code, create an instance of the Credentials class to authenticate with Google Cloud Platform:
CredentialsProvider credentialsProvider = null;
try {
credentialsProvider = FixedCredentialsProvider
.create(ServiceAccountCredentials
.fromStream(new ByteArrayInputStream(
StandardCharsets.UTF_8.encode("AccountCredential").array()
)));
} catch (Exception e) {
}
Replace <AccountCredential> with your credentials.
You can download this file from the Google Cloud Console.
- Create an instance of the
Publisherclass from the Google Cloud Pub/Sub client library, passing the credentials and the name of the topic you want to publish to:
Publisher publisher = Publisher.newBuilder(topic)
.setCredentialsProvider(credentialsProvider)
.build()
- Create a
PubsubMessageobject to represent the message you want to publish:
ByteString data = ByteString.copyFromUtf8("Message Content");
PubsubMessage pubsubMessage = PubsubMessage.newBuilder().setData(data).build();
- Publish the message to the topic using the
publishmethod of thePublisherinstance:
ApiFuture<String> messageIdFuture = publisher.publish(pubsubMessage);
String messageId = messageIdFuture.get();
ApiFutures.addCallback(messageIdFuture, new ApiFutureCallback<String>() {
public void onSuccess(String messageId) {
}
public void onFailure(Throwable t) {
}
}, MoreExecutors.directExecutor());
} catch (Exception e) {
}
- Close the
Publisherinstance after publishing the message:
publisher.shutdown();
publisher.awaitTermination(1, TimeUnit.MINUTES);
} catch (Exception e) {
}
GitHub project link of reusable module.
git clone https://github.com/tariqulgithub/gcloud-pubsub.git 2. Compile and Install.
mvn clean install <dependency>
<groupId>org.simpleton</groupId>
<artifactId>gcloud-pubsub</artifactId>
<version>1.0.0</version>
</dependency> String credentialString = "";
JSONObject messageBody = new JSONObject();
messageBody.put("Hello", "Hello From Inline");
GAccountCredentials gAccountCredentials = GAccountCredentials.builder()
.accountCredential(credentialString)
.projectId("projectId")
.topic("myTopic")
.build();
GCloudMessagePublisher publisher = GCloudMessagePublisher.getInstance();
publisher.publishMessage(MessageContainer.builder()
.content(messageBody.toString())
.build(), gAccountCredentials);
publisher.shutdown(); How to publish and receive a message in pub/sub in cloud console?
First, we need to Set up a Google Cloud console project.
- Create or select a project.
- Enable the Pub/Sub API for that project.
Create a Topic:
- In a google cloud console, navigate to the pub-sub page.
- Click on create topic button and enter a unique name
Subscribe to the Topic:
Publish a message on the topic:
- To publish a message on the created topic, click on a topic
- Click on the message tab
- Select Subscription
- Click Publish Message
- In the Message body, add the message
- Click Publish. A message at the bottom of the page says “Message published” if the publication was successful.
Pull the data Published:
- Go to subscriptions, and click on subscription Id
- In the Messages tab, click Pull.
Comments
Post a Comment