Publishers
After you've set everything up andinstantiated aPubsub
client, you can send requests to API. The general flow for a publisher application is as follows:
- Define a topic and send a request to the Pub/Sub system to create it.
- Create a message, and set data and optional attributes on it.
- Send a request to the Pub/Sub Server to publish the message to the desired topic.
The following code samples demonstrate how to send a few simple requests:
See Delete a topic for a discussion of what happens when you delete a topic. For a full list of methods, see thereference documentation.
Create a topic
Here is some sample code to create a topic:
REST API
PUT https://pubsub.googleapis.com/v1/projects/myproject/topics/mytopic
-- Response:
200 OK
{
"name": "projects/myproject/topics/mytopic"
}
Java
try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
// projectId <= unique project identifier, eg. "my-project-id"
// topicId <= "my-topic-id"
TopicName topicName = TopicName.create(projectId, topicId);
Topic topic = topicAdminClient.createTopic(topicName);
return topic;
}
Python
def create_topic(topic_name):
"""Create a new Pub/Sub topic."""
pubsub_client = pubsub.Client()
topic = pubsub_client.topic(topic_name)
topic.create()
print('Topic {} created.'.format(topic.name))
Publish messages to a topic
When using JSON, message data must be base64-encoded, and can be a maximum of 10MB after encoding. (The Java client libraries provide methods for Base64-encoding data.) Note that the message payload must not be empty; it must contain either a non-empty data field, or at least one attribute.
Also, though Pub/Sub usually delivers messages in order of publication, this is not guaranteed; it is possible for subscriptions to receive messages out of order. For this reason, we suggest that you include sequence information in the message payload or attribute so that subscribers that need in-order messaging can implement logic to do so.
REST API
POST https://pubsub.googleapis.com/v1/projects/myproject/topics/mytopic:publish
{
"messages": [
{
"attributes": {
"key": "iana.org/language_tag",
"value": "en"
},
"data": "SGVsbG8gQ2xvdWQgUHViL1N1YiEgSGVyZSBpcyBteSBtZXNzYWdlIQ=="
}
]
}
-- Response:
200 OK
{
"messageIds": [
"19916711285"
]
}
Java
TopicName topicName = TopicName.create("my-project-id", "my-topic-id");
Publisher publisher = null;
List<ApiFuture<String>> messageIdFutures = new ArrayList<>();
try {
// Create a publisher instance with default settings bound to the topic
publisher = Publisher.defaultBuilder(topicName).build();
List<String> messages = Arrays.asList("first message", "second message");
// schedule publishing one message at a time : messages get automatically batched
for (String message : messages) {
ByteString data = ByteString.copyFromUtf8(message);
PubsubMessage pubsubMessage = PubsubMessage.newBuilder().setData(data).build();
// Once published, returns a server-assigned message id (unique within the topic)
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) {
System.out.println("published with message ID: " + messageId);
}
if (publisher != null) {
// When finished with the publisher, shutdown to free up resources.
publisher.shutdown();
}
}
Python
def publish_message(topic_name, data):
"""Publishes a message to a Pub/Sub topic with the given data."""
pubsub_client = pubsub.Client()
topic = pubsub_client.topic(topic_name)
# Data must be a bytestring
data = data.encode('utf-8')
message_id = topic.publish(data)
print('Message {} published.'.format(message_id))
List topics in a project
By default, a maximum of 100 results are returned per query; you can specify an alternate value up to 1,000 in thepageSize
query parameter.
REST API
GET https://pubsub.googleapis.com/v1/projects/myproject/topics
-- Response:
200 OK
{
"topics": [
{
"name": "projects/myproject/topics/mytopic1"
},
{
"name": "projects/myproject/topics/mytopic2"
}
]
}
Java
try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
ListTopicsRequest listTopicsRequest =
ListTopicsRequest.newBuilder()
.setProjectWithProjectName(ProjectName.create(projectId))
.build();
ListTopicsPagedResponse response = topicAdminClient.listTopics(listTopicsRequest);
Iterable<Topic> topics = response.iterateAll();
for (Topic topic : topics) {
// do something with the topic
}
return response;
}
Python
def list_topics():
"""Lists all Pub/Sub topics in the current project."""
pubsub_client = pubsub.Client()
for topic in pubsub_client.list_topics():
print(topic.name)
Delete a topic
When you delete a topic, its subscriptions are not deleted, and the subscriptions' backlog is available. After a topic is deleted, its subscriptions have the topic name _deleted-topic_.
Java
try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
TopicName topicName = TopicName.create(projectId, topicId);
topicAdminClient.deleteTopic(topicName);
return topicName;
}
Python
def delete_topic(topic_name):
"""Deletes an existing Pub/Sub topic."""
pubsub_client = pubsub.Client()
topic = pubsub_client.topic(topic_name)
topic.delete()
print('Topic {} deleted.'.format(topic.name))