更新主题架构
深入探索
如需查看包含此代码示例的详细文档,请参阅以下内容:
代码示例
C++
试用此示例之前,请按照 Pub/Sub 快速入门:使用客户端库中的 C++ 设置说明进行操作。如需了解详情,请参阅 Pub/Sub C++ API 参考文档。
要向 Pub/Sub 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证。
namespace pubsub = ::google::cloud::pubsub;
namespace pubsub_admin = ::google::cloud::pubsub_admin;
[](pubsub_admin::TopicAdminClient client, std::string project_id,
std::string topic_id, std::string const& first_revision_id,
std::string const& last_revision_id) {
google::pubsub::v1::UpdateTopicRequest request;
auto* request_topic = request.mutable_topic();
request_topic->set_name(
pubsub::Topic(std::move(project_id), std::move(topic_id)).FullName());
request_topic->mutable_schema_settings()->set_first_revision_id(
first_revision_id);
request_topic->mutable_schema_settings()->set_last_revision_id(
last_revision_id);
*request.mutable_update_mask()->add_paths() =
"schema_settings.first_revision_id";
*request.mutable_update_mask()->add_paths() =
"schema_settings.last_revision_id";
auto topic = client.UpdateTopic(request);
if (!topic) throw std::move(topic).status();
std::cout << "The topic was successfully updated: " << topic->DebugString()
<< "\n";
}
C#
试用此示例之前,请按照 Pub/Sub 快速入门:使用客户端库中的 C# 设置说明进行操作。如需了解详情,请参阅 Pub/Sub C# API 参考文档。
要向 Pub/Sub 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证。
using Google.Cloud.PubSub.V1;
using Google.Protobuf.WellKnownTypes;
using System;
public class UpdateTopicSchemaSample
{
public Topic UpdateTopicSchema(string projectId, string topicId, string firstRevisionId, string lastRevisionId)
{
PublisherServiceApiClient publisher = PublisherServiceApiClient.Create();
var topicName = TopicName.FromProjectTopic(projectId, topicId);
Topic topic = new Topic
{
TopicName = topicName,
SchemaSettings = new SchemaSettings
{
FirstRevisionId = firstRevisionId,
LastRevisionId = lastRevisionId
}
};
FieldMask updateMask = new FieldMask { Paths = { "schema_settings.first_revision_id", "schema_settings.last_revision_id" } };
Topic receivedTopic = publisher.UpdateTopic(topic, updateMask);
Console.WriteLine($"Topic {topic.Name} updated.");
return receivedTopic;
}
}
Go
试用此示例之前,请按照 Pub/Sub 快速入门:使用客户端库中的 Go 设置说明进行操作。如需了解详情,请参阅 Pub/Sub Go API 参考文档。
要向 Pub/Sub 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证。
import (
"context"
"fmt"
"io"
"cloud.google.com/go/pubsub"
)
func updateTopicSchema(w io.Writer, projectID, topicID, firstRevisionID, lastRevisionID string) error {
// projectID := "my-project-id"
// topicID := "my-topic"
// firstRevisionID := "my-revision-id"
// lastRevisionID := "my-revision-id"
ctx := context.Background()
client, err := pubsub.NewClient(ctx, projectID)
if err != nil {
return fmt.Errorf("pubsub.NewClient: %w", err)
}
t := client.Topic(topicID)
// This updates the first / last revision ID for the topic's schema.
// To clear the schema entirely, use a zero valued (empty) SchemaSettings.
tc := pubsub.TopicConfigToUpdate{
SchemaSettings: &pubsub.SchemaSettings{
FirstRevisionID: firstRevisionID,
LastRevisionID: lastRevisionID,
},
}
gotTopicCfg, err := t.Update(ctx, tc)
if err != nil {
fmt.Fprintf(w, "topic.Update err: %v\n", gotTopicCfg)
return err
}
fmt.Fprintf(w, "Updated topic with schema: %#v\n", gotTopicCfg)
return nil
}
Java
试用此示例之前,请按照 Pub/Sub 快速入门:使用客户端库中的 Java 设置说明进行操作。如需了解详情,请参阅 Pub/Sub Java API 参考文档。
要向 Pub/Sub 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证。
import com.google.cloud.pubsub.v1.TopicAdminClient;
import com.google.protobuf.FieldMask;
import com.google.pubsub.v1.SchemaSettings;
import com.google.pubsub.v1.Topic;
import com.google.pubsub.v1.TopicName;
import com.google.pubsub.v1.UpdateTopicRequest;
import java.io.IOException;
public class UpdateTopicSchemaExample {
public static void main(String... args) throws Exception {
// TODO(developer): Replace these variables before running the sample.
String projectId = "your-project-id";
// This is an existing topic that has schema settings attached to it.
String topicId = "your-topic-id";
// Set the minimum and maximum revsion ID
String firstRevisionId = "your-revision-id";
String lastRevisionId = "your-revision-id";
UpdateTopicSchemaExample.updateTopicSchemaExample(
projectId, topicId, firstRevisionId, lastRevisionId);
}
public static void updateTopicSchemaExample(
String projectId, String topicId, String firstRevisionid, String lastRevisionId)
throws IOException {
try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
TopicName topicName = TopicName.of(projectId, topicId);
// Construct the schema settings with the changes you want to make.
SchemaSettings schemaSettings =
SchemaSettings.newBuilder()
.setFirstRevisionId(firstRevisionid)
.setLastRevisionId(lastRevisionId)
.build();
// Construct the topic with the schema settings you want to change.
Topic topic =
Topic.newBuilder()
.setName(topicName.toString())
.setSchemaSettings(schemaSettings)
.build();
// Construct a field mask to indicate which field to update in the topic.
FieldMask updateMask =
FieldMask.newBuilder()
.addPaths("schema_settings.first_revision_id")
.addPaths("schema_settings.last_revision_id")
.build();
UpdateTopicRequest request =
UpdateTopicRequest.newBuilder().setTopic(topic).setUpdateMask(updateMask).build();
Topic response = topicAdminClient.updateTopic(request);
System.out.println("Updated topic with schema: " + topic.getName());
}
}
}
Node.js
/**
* TODO(developer): Uncomment these variables before running the sample.
*/
// const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID';
// const firstRevisionId = 'YOUR_REVISION_ID';
// const lastRevisionId = 'YOUR_REVISION_ID';
// Imports the Google Cloud client library
const {PubSub} = require('@google-cloud/pubsub');
// Creates a client; cache this for further use
const pubSubClient = new PubSub();
async function updateTopicSchema(
topicNameOrId,
firstRevisionId,
lastRevisionId
) {
const metadata = {
schemaSettings: {
firstRevisionId,
lastRevisionId,
},
};
await pubSubClient.topic(topicNameOrId).setMetadata(metadata);
console.log('Schema metadata updated successfully.');
}
Node.js
/**
* TODO(developer): Uncomment these variables before running the sample.
*/
// const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID';
// const firstRevisionId = 'YOUR_REVISION_ID';
// const lastRevisionId = 'YOUR_REVISION_ID';
// Imports the Google Cloud client library
import {PubSub, TopicMetadata} from '@google-cloud/pubsub';
// Creates a client; cache this for further use
const pubSubClient = new PubSub();
async function updateTopicSchema(
topicNameOrId: string,
firstRevisionId: string,
lastRevisionId: string
) {
const metadata: TopicMetadata = {
schemaSettings: {
firstRevisionId,
lastRevisionId,
},
};
await pubSubClient.topic(topicNameOrId).setMetadata(metadata);
console.log('Schema metadata updated successfully.');
}
PHP
试用此示例之前,请按照 Pub/Sub 快速入门:使用客户端库中的 PHP 设置说明进行操作。如需了解详情,请参阅 Pub/Sub PHP API 参考文档。
要向 Pub/Sub 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证。
use Google\Cloud\PubSub\PubSubClient;
/**
* Update schema for a topic.
*
* @param string $projectId The ID of your Google Cloud Platform project.
* @param string $topicId The topic id of an existing topic that has schema
* settings attached to it.
* @param string $firstRevisionId The minimum revision id
* @param string $lastRevisionId The maximum revision id
*/
function update_topic_schema(
string $projectId,
string $topicId,
string $firstRevisionId,
string $lastRevisionId,
): void {
$pubsub = new PubSubClient([
'projectId' => $projectId
]);
$topic = $pubsub->topic($topicId);
$topic->update([
'schemaSettings' => [
// Minimum revision ID
'firstRevisionId' => $firstRevisionId,
// Maximum revision ID
'lastRevisionId' => $lastRevisionId
]
]);
printf('Updated topic with schema: %s', $topic->name());
}
Python
试用此示例之前,请按照 Pub/Sub 快速入门:使用客户端库中的 Python 设置说明进行操作。如需了解详情,请参阅 Pub/Sub Python API 参考文档。
要向 Pub/Sub 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证。
from google.api_core.exceptions import InvalidArgument, NotFound
from google.cloud.pubsub import PublisherClient
# TODO(developer): Replace these variables before running the sample.
# project_id = "your-project-id"
# topic_id = "your-topic-id"
# first_revision_id = "your-revision-id"
# last_revision_id = "your-revision-id"
publisher_client = PublisherClient()
topic_path = publisher_client.topic_path(project_id, topic_id)
try:
response = publisher_client.update_topic(
request={
"topic": {
"name": topic_path,
"schema_settings": {
"first_revision_id": first_revision_id,
"last_revision_id": last_revision_id,
},
},
"update_mask": "schemaSettings.firstRevisionId,schemaSettings.lastRevisionId",
}
)
print(f"Updated a topic schema:\n{response}")
except NotFound:
print(f"{topic_id} not found.")
except InvalidArgument:
print("Schema settings are not valid.")
后续步骤
如需搜索和过滤其他 Google Cloud 产品的代码示例,请参阅 Google Cloud 示例浏览器。