Integrate Google Cloud Pub/Sub in Java
- Add the Pub/Sub dependency to your project. Ensure that your `pom.xml` includes the necessary dependency for Pub/Sub if you're using Maven.
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-pubsub</artifactId>
<version>1.116.3</version> <!-- Ensure this is the latest version -->
</dependency>
- Initialize the Pub/Sub client. Use Google's credential setup to authenticate and interact with the Pub/Sub API within your Java application.
import com.google.cloud.pubsub.v1.Publisher;
import com.google.cloud.pubsub.v1.Subscriber;
import com.google.pubsub.v1.ProjectTopicName;
import com.google.pubsub.v1.ProjectSubscriptionName;
import com.google.pubsub.v1.PubsubMessage;
import com.google.api.core.ApiFuture;
import com.google.api.core.ApiFutures;
import com.google.api.gax.rpc.ApiException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
String projectId = "your-project-id";
String topicId = "your-topic-id";
// Create a topic name
ProjectTopicName topicName = ProjectTopicName.of(projectId, topicId);
- Publish a message. Use the `Publisher` class from the library to publish messages to your topic.
Publisher publisher = null;
try {
// Create a publisher instance with default settings
publisher = Publisher.newBuilder(topicName).build();
String message = "Hello, Pub/Sub!";
ByteString data = ByteString.copyFromUtf8(message);
PubsubMessage pubsubMessage = PubsubMessage.newBuilder().setData(data).build();
// Schedule a message to be published
ApiFuture<String> messageIdFuture = publisher.publish(pubsubMessage);
// Add a callback
ApiFutures.addCallback(messageIdFuture, new ApiFutureCallback<String>() {
@Override
public void onSuccess(String messageId) {
System.out.println("Published with message ID: " + messageId);
}
@Override
public void onFailure(Throwable t) {
System.out.println("Failed to publish: " + t);
}
}, MoreExecutors.directExecutor());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (publisher != null) {
try {
publisher.shutdown();
publisher.awaitTermination(1, TimeUnit.MINUTES);
} catch (Exception e) {
e.printStackTrace();
}
}
}
- Subscribe to a topic. Implement a subscriber to process messages received in a subscription.
String subscriptionId = "your-subscription-id";
// Create a subscription name
ProjectSubscriptionName subscriptionName = ProjectSubscriptionName.of(projectId, subscriptionId);
MessageReceiver receiver =
(PubsubMessage message, AckReplyConsumer consumer) -> {
System.out.println("Message Id: " + message.getMessageId());
System.out.println("Data: " + message.getData().toStringUtf8());
consumer.ack();
};
Subscriber subscriber = null;
try {
subscriber = Subscriber.newBuilder(subscriptionName, receiver).build();
subscriber.startAsync().awaitRunning();
// Allow the subscriber to run indefinitely unless an error occurs
subscriber.awaitTerminated();
} catch (TimeoutException e) {
subscriber.stopAsync();
}
- Handle exceptions and cleanup resources. Ensure that resources like `Publisher` and `Subscriber` are shut down gracefully to prevent resource leaks or unintended behavior.
try {
if (publisher != null) {
publisher.shutdown();
publisher.awaitTermination(1, TimeUnit.MINUTES);
}
if (subscriber != null) {
subscriber.stopAsync();
}
} catch (Exception e) {
e.printStackTrace();
}
- Test your implementation. Once you've integrated Pub/Sub into your application, perform tests to ensure messages are correctly published and received.