修改主题。关联架构并指定修订版本。
深入探索
如需查看包含此代码示例的详细文档,请参阅以下内容:
代码示例
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 schema_id, std::string const& encoding,
std::string const& first_revision_id,
std::string const& last_revision_id) {
google::pubsub::v1::Topic request;
request.set_name(pubsub::Topic(project_id, std::move(topic_id)).FullName());
request.mutable_schema_settings()->set_schema(
pubsub::Schema(std::move(project_id), std::move(schema_id)).FullName());
request.mutable_schema_settings()->set_encoding(
encoding == "JSON" ? google::pubsub::v1::JSON
: google::pubsub::v1::BINARY);
request.mutable_schema_settings()->set_first_revision_id(first_revision_id);
request.mutable_schema_settings()->set_last_revision_id(last_revision_id);
auto topic = client.CreateTopic(request);
// Note that kAlreadyExists is a possible error when the
// library retries.
if (topic.status().code() == google::cloud::StatusCode::kAlreadyExists) {
std::cout << "The topic already exists\n";
return;
}
if (!topic) throw std::move(topic).status();
std::cout << "The topic was successfully created: " << topic->DebugString()
<< "\n";
}
C#
试用此示例之前,请按照 Pub/Sub 快速入门:使用客户端库中的 C# 设置说明进行操作。如需了解详情,请参阅 Pub/Sub C# API 参考文档。
要向 Pub/Sub 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证。
using Google.Cloud.PubSub.V1;
using Grpc.Core;
using System;
public class CreateTopicWithSchemaRevisionsSample
{
public Topic CreateTopicWithSchemaRevisions(string projectId, string topicId, string schemaId, string firstRevisionId, string lastRevisionId, Encoding encoding)
{
PublisherServiceApiClient publisher = PublisherServiceApiClient.Create();
var topicName = TopicName.FromProjectTopic(projectId, topicId);
Topic topic = new Topic
{
TopicName = topicName,
SchemaSettings = new SchemaSettings
{
SchemaAsSchemaName = SchemaName.FromProjectSchema(projectId, schemaId),
FirstRevisionId = firstRevisionId,
LastRevisionId = lastRevisionId,
Encoding = encoding,
}
};
Topic receivedTopic = null;
try
{
receivedTopic = publisher.CreateTopic(topic);
Console.WriteLine($"Topic {topic.Name} created.");
}
catch (RpcException e) when (e.Status.StatusCode == StatusCode.AlreadyExists)
{
Console.WriteLine($"Topic {topicName} already exists.");
}
return receivedTopic;
}
}
Go
试用此示例之前,请按照 Pub/Sub 快速入门:使用客户端库中的 Go 设置说明进行操作。如需了解详情,请参阅 Pub/Sub Go API 参考文档。
要向 Pub/Sub 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证。
import (
"context"
"fmt"
"io"
"cloud.google.com/go/pubsub"
)
func createTopicWithSchemaRevisions(w io.Writer, projectID, topicID, schemaID, firstRevisionID, lastRevisionID string, encoding pubsub.SchemaEncoding) error {
// projectID := "my-project-id"
// topicID := "my-topic"
// schemaID := "my-schema-id"
// firstRevisionID := "my-revision-id"
// lastRevisionID := "my-revision-id"
// encoding := pubsub.EncodingJSON
ctx := context.Background()
client, err := pubsub.NewClient(ctx, projectID)
if err != nil {
return fmt.Errorf("pubsub.NewClient: %w", err)
}
tc := &pubsub.TopicConfig{
SchemaSettings: &pubsub.SchemaSettings{
Schema: fmt.Sprintf("projects/%s/schemas/%s", projectID, schemaID),
FirstRevisionID: firstRevisionID,
LastRevisionID: lastRevisionID,
Encoding: encoding,
},
}
t, err := client.CreateTopicWithConfig(ctx, topicID, tc)
if err != nil {
return fmt.Errorf("CreateTopicWithConfig: %w", err)
}
fmt.Fprintf(w, "Created topic with schema revision: %#v\n", t)
return nil
}
Java
试用此示例之前,请按照 Pub/Sub 快速入门:使用客户端库中的 Java 设置说明进行操作。如需了解详情,请参阅 Pub/Sub Java API 参考文档。
要向 Pub/Sub 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证。
import com.google.api.gax.rpc.AlreadyExistsException;
import com.google.cloud.pubsub.v1.TopicAdminClient;
import com.google.pubsub.v1.Encoding;
import com.google.pubsub.v1.SchemaName;
import com.google.pubsub.v1.SchemaSettings;
import com.google.pubsub.v1.Topic;
import com.google.pubsub.v1.TopicName;
import java.io.IOException;
public class CreateTopicWithSchemaRevisionsExample {
public static void main(String... args) throws Exception {
// TODO(developer): Replace these variables before running the sample.
String projectId = "your-project-id";
String topicId = "your-topic-id";
// Use an existing schema.
String schemaId = "your-schema-id";
// Choose either BINARY or JSON message serialization in this topic.
Encoding encoding = Encoding.BINARY;
// Set the minimum and maximum revsion ID
String firstRevisionId = "your-revision-id";
String lastRevisionId = "your-revision-id";
createTopicWithSchemaRevisionsExample(
projectId, topicId, schemaId, firstRevisionId, lastRevisionId, encoding);
}
public static void createTopicWithSchemaRevisionsExample(
String projectId,
String topicId,
String schemaId,
String firstRevisionid,
String lastRevisionId,
Encoding encoding)
throws IOException {
TopicName topicName = TopicName.of(projectId, topicId);
SchemaName schemaName = SchemaName.of(projectId, schemaId);
SchemaSettings schemaSettings =
SchemaSettings.newBuilder()
.setSchema(schemaName.toString())
.setFirstRevisionId(firstRevisionid)
.setLastRevisionId(lastRevisionId)
.setEncoding(encoding)
.build();
try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
Topic topic =
topicAdminClient.createTopic(
Topic.newBuilder()
.setName(topicName.toString())
.setSchemaSettings(schemaSettings)
.build());
System.out.println("Created topic with schema: " + topic.getName());
} catch (AlreadyExistsException e) {
System.out.println(schemaName + "already exists.");
}
}
}
Node.js
/**
* TODO(developer): Uncomment these variables before running the sample.
*/
// const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID';
// const schemaName = 'YOUR_SCHEMA_NAME_OR_ID';
// const encodingType = 'BINARY';
// 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 createTopicWithSchemaRevisions(
topicNameOrId,
schemaNameOrId,
encodingType,
firstRevisionId,
lastRevisionId
) {
// Get the fully qualified schema name.
const schema = pubSubClient.schema(schemaNameOrId);
const fullName = await schema.getName();
// Creates a new topic with a schema. Note that you might also
// pass Encodings.Json or Encodings.Binary here.
await pubSubClient.createTopic({
name: topicNameOrId,
schemaSettings: {
schema: fullName,
encoding: encodingType,
firstRevisionId,
lastRevisionId,
},
});
console.log(`Topic ${topicNameOrId} created with schema ${fullName}.`);
}
Node.js
/**
* TODO(developer): Uncomment these variables before running the sample.
*/
// const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID';
// const schemaName = 'YOUR_SCHEMA_NAME_OR_ID';
// const encodingType = 'BINARY';
// const firstRevisionId = 'YOUR_REVISION_ID';
// const lastRevisionId = 'YOUR_REVISION_ID';
// Imports the Google Cloud client library
import {PubSub} from '@google-cloud/pubsub';
// Creates a client; cache this for further use
const pubSubClient = new PubSub();
async function createTopicWithSchemaRevisions(
topicNameOrId: string,
schemaNameOrId: string,
encodingType: 'BINARY' | 'JSON',
firstRevisionId: string,
lastRevisionId: string
) {
// Get the fully qualified schema name.
const schema = pubSubClient.schema(schemaNameOrId);
const fullName = await schema.getName();
// Creates a new topic with a schema. Note that you might also
// pass Encodings.Json or Encodings.Binary here.
await pubSubClient.createTopic({
name: topicNameOrId,
schemaSettings: {
schema: fullName,
encoding: encodingType,
firstRevisionId,
lastRevisionId,
},
});
console.log(`Topic ${topicNameOrId} created with schema ${fullName}.`);
}
PHP
试用此示例之前,请按照 Pub/Sub 快速入门:使用客户端库中的 PHP 设置说明进行操作。如需了解详情,请参阅 Pub/Sub PHP API 参考文档。
要向 Pub/Sub 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证。
use Google\Cloud\PubSub\PubSubClient;
use Google\Cloud\PubSub\Schema;
/**
* Create a topic with schema revisions.
*
* @param string $projectId Your Google Cloud Project ID.
* @param string $topicId Topic ID for the new topic.
* @param string $schemaId Existing schema id
* @param string $firstRevisionId Minimum revision Id
* @param string $lastRevisionId Maximum revision Id
* @param string $encoding Either BINARY or JSON
*/
function create_topic_with_schema_revisions(
string $projectId,
string $topicId,
string $schemaId,
string $firstRevisionId,
string $lastRevisionId,
string $encoding
) {
$pubsub = new PubSubClient([
'projectId' => $projectId,
]);
$schema = $pubsub->schema($schemaId);
$topic = $pubsub->createTopic($topicId, [
'schemaSettings' => [
'schema' => $schema,
'encoding' => $encoding,
'firstRevisionId' => $firstRevisionId,
'lastRevisionId' => $lastRevisionId,
]
]);
printf('Topic %s created', $topic->name());
}
Python
试用此示例之前,请按照 Pub/Sub 快速入门:使用客户端库中的 Python 设置说明进行操作。如需了解详情,请参阅 Pub/Sub Python API 参考文档。
要向 Pub/Sub 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证。
from google.api_core.exceptions import AlreadyExists, InvalidArgument
from google.cloud.pubsub import PublisherClient, SchemaServiceClient
from google.pubsub_v1.types import Encoding
# TODO(developer): Replace these variables before running the sample.
# project_id = "your-project-id"
# topic_id = "your-topic-id"
# schema_id = "your-schema-id"
# first_revision_id = "your-revision-id"
# last_revision_id = "your-revision-id"
# Choose either BINARY or JSON as valid message encoding in this topic.
# message_encoding = "BINARY"
publisher_client = PublisherClient()
topic_path = publisher_client.topic_path(project_id, topic_id)
schema_client = SchemaServiceClient()
schema_path = schema_client.schema_path(project_id, schema_id)
if message_encoding == "BINARY":
encoding = Encoding.BINARY
elif message_encoding == "JSON":
encoding = Encoding.JSON
else:
encoding = Encoding.ENCODING_UNSPECIFIED
try:
response = publisher_client.create_topic(
request={
"name": topic_path,
"schema_settings": {
"schema": schema_path,
"encoding": encoding,
"first_revision_id": first_revision_id,
"last_revision_id": last_revision_id,
},
}
)
print(f"Created a topic:\n{response}")
except AlreadyExists:
print(f"{topic_id} already exists.")
except InvalidArgument:
print("Please choose either BINARY or JSON as a valid message encoding type.")
后续步骤
如需搜索和过滤其他 Google Cloud 产品的代码示例,请参阅 Google Cloud 示例浏览器。