Skip to content

Repository files navigation

Google Cloud Pub/Sub Lite Client for Java

Java idiomatic client for Cloud Pub/Sub Lite.

MavenStability

Note: This client is a work-in-progress, and may occasionally make backwards-incompatible changes.

Quickstart

If you are using Maven, add this to your pom.xml file:

<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-pubsublite</artifactId>
<version>0.11.1</version>
</dependency>
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-pubsub</artifactId>
<version>1.111.4</version>
</dependency>

If you are using Gradle without BOM, add this to your dependencies

compile 'com.google.cloud:google-cloud-pubsublite:0.11.1'

If you are using SBT, add this to your dependencies

libraryDependencies +="com.google.cloud"%"google-cloud-pubsublite"%"0.11.1"

Authentication

See the Authentication section in the base directory's README.

Getting Started

Prerequisites

You will need a Google Cloud Platform Console project with the Cloud Pub/Sub Lite API enabled. You will need to enable billing to use Google Cloud Pub/Sub Lite. Follow these instructions to get your project set up. You will also need to set up the local development environment by installing the Google Cloud SDK and running the following commands in command line: gcloud auth login and gcloud config set project [YOUR PROJECT ID].

Installation and setup

You'll need to obtain the google-cloud-pubsublite library. See the Quickstart section to add google-cloud-pubsublite as a dependency in your code.

About Cloud Pub/Sub Lite

Google Pub/Sub Lite is designed to provide reliable, many-to-many, asynchronous messaging between applications. Publisher applications can send messages to a topic and other applications can subscribe to that topic to receive the messages. By decoupling senders and receivers, Google Cloud Pub/Sub allows developers to communicate between independently written applications.

Compared to Google Pub/Sub, Pub/Sub Lite provides partitioned zonal data storage with predefined capacity. Both products present a similar API, but Pub/Sub Lite has more usage caveats.

See the Google Pub/Sub Lite docs for more details on how to activate Pub/Sub Lite for your project, as well as guidance on how to choose between Cloud Pub/Sub and Pub/Sub Lite.

Creating a topic

With Pub/Sub Lite you can create topics. A topic is a named resource to which messages are sent by publishers. Add the following imports at the top of your file:

importcom.google.cloud.pubsublite.*;
importcom.google.cloud.pubsublite.proto.Topic;
importcom.google.cloud.pubsublite.proto.Topic.*;
importcom.google.protobuf.util.Durations;

Then, to create the topic, use the following code:

// TODO(developer): Replace these variables with your own.longprojectNumber = 123L;
StringcloudRegion = "us-central1";
charzoneId = 'b';
StringtopicId = "your-topic-id";
Integerpartitions = 1;
TopicPathtopicPath =
TopicPath.newBuilder()
.setProject(ProjectNumber.of(projectNumber))
.setLocation(CloudZone.of(CloudRegion.of(cloudRegion), zoneId))
.setName(TopicName.of(topicId))
.build();
Topictopic =
Topic.newBuilder()
.setPartitionConfig(
PartitionConfig.newBuilder()
// Set publishing throughput to 1 times the standard partition// throughput of 4 MiB per sec. This must be in the range [1,4]. A// topic with `scale` of 2 and count of 10 is charged for 20 partitions.
.setScale(1)
.setCount(partitions))
.setRetentionConfig(
RetentionConfig.newBuilder()
// How long messages are retained.
.setPeriod(Durations.fromDays(1))
// Set storage per partition to 30 GiB. This must be 30 GiB-10 TiB.// If the number of bytes stored in any of the topic's partitions grows// beyond this value, older messages will be dropped to make room for// newer ones, regardless of the value of `period`.
.setPerPartitionBytes(30 * 1024 * 1024 * 1024L))
.setName(topicPath.toString())
.build();
AdminClientSettingsadminClientSettings =
AdminClientSettings.newBuilder().setRegion(CloudRegion.of(cloudRegion)).build();
try (AdminClientadminClient = AdminClient.create(adminClientSettings)) {
Topicresponse = adminClient.createTopic(topic).get();
System.out.println(response.getAllFields() + "created successfully.");
}

Publishing messages

With Pub/Sub Lite, you can publish messages to a topic. Add the following import at the top of your file:

importcom.google.api.core.*;
importcom.google.cloud.pubsublite.*;
importcom.google.cloud.pubsublite.cloudpubsub.*;
importcom.google.protobuf.ByteString;
importcom.google.pubsub.v1.PubsubMessage;
importjava.util.*;

Then, to publish messages asynchronously, use the following code:

// TODO(developer): Replace these variables before running the sample.longprojectNumber = 123L;
StringcloudRegion = "us-central1";
charzoneId = 'b';
// Choose an existing topic.StringtopicId = "your-topic-id";
intmessageCount = 100;
TopicPathtopicPath =
TopicPath.newBuilder()
.setProject(ProjectNumber.of(projectNumber))
.setLocation(CloudZone.of(CloudRegion.of(cloudRegion), zoneId))
.setName(TopicName.of(topicId))
.build();
Publisherpublisher = null;
List<ApiFuture<String>> futures = newArrayList<>();
try {
PublisherSettingspublisherSettings =
PublisherSettings.newBuilder().setTopicPath(topicPath).build();
publisher = Publisher.create(publisherSettings);
// Start the publisher. Upon successful starting, its state will become RUNNING.publisher.startAsync().awaitRunning();
for (inti = 0; i < messageCount; i++) {
Stringmessage = "message-" + i;
// Convert the message to a byte string.ByteStringdata = ByteString.copyFromUtf8(message);
PubsubMessagepubsubMessage = PubsubMessage.newBuilder().setData(data).build();
// Publish a message. Messages are automatically batched.ApiFuture<String> future = publisher.publish(pubsubMessage);
futures.add(future);
}
} finally {
ArrayList<MessageMetadata> metadata = newArrayList<>();
List<String> ackIds = ApiFutures.allAsList(futures).get();
for (Stringid : ackIds) {
// Decoded metadata contains partition and offset.metadata.add(MessageMetadata.decode(id));
}
System.out.println(metadata + "\nPublished " + ackIds.size() + " messages.");
if (publisher != null) {
// Shut down the publisher.publisher.stopAsync().awaitTerminated();
System.out.println("Publisher is shut down.");
}
}

Creating a subscription

With Pub/Sub Lite you can create subscriptions. A subscription represents the stream of messages from a single, specific topic. Add the following imports at the top of your file:

importcom.google.cloud.pubsublite.*;
importcom.google.cloud.pubsublite.proto.Subscription;
importcom.google.cloud.pubsublite.proto.Subscription.*;
importcom.google.cloud.pubsublite.proto.Subscription.DeliveryConfig.*;

Then, to create the subscription, use the following code:

// TODO(developer): Replace these variables with your own.longprojectNumber = 123L;
StringcloudRegion = "us-central1";
charzoneId = 'b';
// Choose an existing topic.StringtopicId = "your-topic-id";
StringsubscriptionId = "your-subscription-id";
TopicPathtopicPath =
TopicPath.newBuilder()
.setProject(ProjectNumber.of(projectNumber))
.setLocation(CloudZone.of(CloudRegion.of(cloudRegion), zoneId))
.setName(TopicName.of(topicId))
.build();
SubscriptionPathsubscriptionPath =
SubscriptionPath.newBuilder()
.setLocation(CloudZone.of(CloudRegion.of(cloudRegion), zoneId))
.setProject(ProjectNumber.of(projectNumber))
.setName(SubscriptionName.of(subscriptionId))
.build();
Subscriptionsubscription =
Subscription.newBuilder()
.setDeliveryConfig(
// The server does not wait for a published message to be successfully// written to storage before delivering it to subscribers. As such, a// subscriber may receive a message for which the write to storage failed.// If the subscriber re-reads the offset of that message later on, there// may be a gap at that offset.DeliveryConfig.newBuilder()
.setDeliveryRequirement(DeliveryRequirement.DELIVER_IMMEDIATELY))
.setName(subscriptionPath.toString())
.setTopic(topicPath.toString())
.build();
AdminClientSettingsadminClientSettings =
AdminClientSettings.newBuilder().setRegion(CloudRegion.of(cloudRegion)).build();
try (AdminClientadminClient = AdminClient.create(adminClientSettings)) {
Subscriptionresponse = adminClient.createSubscription(subscription).get();
System.out.println(response.getAllFields() + "created successfully.");
}

Receiving messages

With Pub/Sub Lite you can receive messages from a subscription. Add the following imports at the top of your file:

importcom.google.cloud.pubsub.v1.AckReplyConsumer;
importcom.google.cloud.pubsub.v1.MessageReceiver;
importcom.google.cloud.pubsublite.*;
importcom.google.cloud.pubsublite.cloudpubsub.*;
importcom.google.common.util.concurrent.MoreExecutors;
importcom.google.pubsub.v1.PubsubMessage;
importjava.util.*;

Then, to pull messages asynchronously, use the following code:

// TODO(developer): Replace these variables with your own.longprojectNumber = 123L;
StringcloudRegion = "us-central1";
charzoneId = 'b';
// Choose an existing topic.StringtopicId = "your-topic-id";
// Choose an existing subscription.StringsubscriptionId = "your-subscription-id";
SubscriptionPathsubscriptionPath =
SubscriptionPath.newBuilder()
.setLocation(CloudZone.of(CloudRegion.of(cloudRegion), zoneId))
.setProject(ProjectNumber.of(projectNumber))
.setName(SubscriptionName.of(subscriptionId))
.build();
// The message stream is paused based on the maximum size or number of messages that the// subscriber has already received, whichever condition is met first.FlowControlSettingsflowControlSettings =
FlowControlSettings.builder()
// 10 MiB. Must be greater than the allowed size of the largest message (1 MiB).
.setBytesOutstanding(10 * 1024 * 1024L)
// 1,000 outstanding messages. Must be >0.
.setMessagesOutstanding(1000L)
.build();
MessageReceiverreceiver =
(PubsubMessagemessage, AckReplyConsumerconsumer) -> {
System.out.println("Id : " + message.getMessageId());
System.out.println("Data : " + message.getData().toStringUtf8());
consumer.ack();
};
SubscriberSettingssubscriberSettings =
SubscriberSettings.newBuilder()
.setSubscriptionPath(subscriptionPath)
.setReceiver(receiver)
// Flow control settings are set at the partition level.
.setPerPartitionFlowControlSettings(flowControlSettings)
.build();
Subscribersubscriber = Subscriber.create(subscriberSettings);
// Start the subscriber. Upon successful starting, its state will become RUNNING.subscriber.startAsync().awaitRunning();
System.out.println("Listening to messages on " + subscriptionPath.toString() + "...");
try {
System.out.println(subscriber.state());
// Wait 90 seconds for the subscriber to reach TERMINATED state. If it encounters// unrecoverable errors before then, its state will change to FAILED and an// IllegalStateException will be thrown.subscriber.awaitTerminated(90, TimeUnit.SECONDS);
} catch (TimeoutExceptiont) {
// Shut down the subscriber. This will change the state of the subscriber to TERMINATED.subscriber.stopAsync().awaitTerminated();
System.out.println("Subscriber is shut down: " + subscriber.state());
}

Samples

Samples are in the samples/ directory. The samples' README.md has instructions for running the samples.

SampleSource CodeTry it
Create Subscription Examplesource codeOpen in Cloud Shell
Create Topic Examplesource codeOpen in Cloud Shell
Delete Subscription Examplesource codeOpen in Cloud Shell
Delete Topic Examplesource codeOpen in Cloud Shell
Get Subscription Examplesource codeOpen in Cloud Shell
Get Topic Examplesource codeOpen in Cloud Shell
List Subscriptions In Project Examplesource codeOpen in Cloud Shell
List Subscriptions In Topic Examplesource codeOpen in Cloud Shell
List Topics Examplesource codeOpen in Cloud Shell
Publish With Batch Settings Examplesource codeOpen in Cloud Shell
Publish With Custom Attributes Examplesource codeOpen in Cloud Shell
Publish With Ordering Key Examplesource codeOpen in Cloud Shell
Publisher Examplesource codeOpen in Cloud Shell
Subscriber Examplesource codeOpen in Cloud Shell
Update Subscription Examplesource codeOpen in Cloud Shell
Update Topic Examplesource codeOpen in Cloud Shell

Troubleshooting

To get help, follow the instructions in the shared Troubleshooting document.

Transport

Cloud Pub/Sub Lite uses gRPC for the transport layer.

Java Versions

Java 8 or above is required for using this client.

Versioning

This library follows Semantic Versioning.

It is currently in major version zero (0.y.z), which means that anything may change at any time and the public API should not be considered stable.

Contributing

Contributions to this library are always welcome and highly encouraged.

See CONTRIBUTING for more information how to get started.

Please note that this project is released with a Contributor Code of Conduct. By participating in this project you agree to abide by its terms. See Code of Conduct for more information.

License

Apache 2.0 - See LICENSE for more information.

CI Status

Java VersionStatus
Java 8Kokoro CI
Java 8 OSXKokoro CI
Java 8 WindowsKokoro CI
Java 11Kokoro CI

Java is a registered trademark of Oracle and/or its affiliates.

About

No description, website, or topics provided.

Resources

Code of conduct

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages