提交协议缓冲区架构的修订版本
深入探索
如需查看包含此代码示例的详细文档,请参阅以下内容:
代码示例
C++
试用此示例之前,请按照 Pub/Sub 快速入门:使用客户端库中的 C++ 设置说明进行操作。如需了解详情,请参阅 Pub/Sub C++ API 参考文档。
要向 Pub/Sub 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证。
namespace pubsub = ::google::cloud::pubsub;
[](pubsub::SchemaServiceClient client, std::string const& project_id,
std::string const& schema_id, std::string const& schema_definition_file) {
std::string const definition = ReadFile(schema_definition_file);
google::pubsub::v1::CommitSchemaRequest request;
std::string const name =
google::cloud::pubsub::Schema(project_id, schema_id).FullName();
request.set_name(name);
request.mutable_schema()->set_name(name);
request.mutable_schema()->set_type(
google::pubsub::v1::Schema::PROTOCOL_BUFFER);
request.mutable_schema()->set_definition(definition);
auto schema = client.CommitSchema(request);
if (schema.status().code() == google::cloud::StatusCode::kAlreadyExists) {
std::cout << "The schema revision already exists\n";
return;
}
if (!schema) throw std::move(schema).status();
std::cout << "Schema revision successfully committed: "
<< schema->DebugString() << "\n";
}
C#
试用此示例之前,请按照 Pub/Sub 快速入门:使用客户端库中的 C# 设置说明进行操作。如需了解详情,请参阅 Pub/Sub C# API 参考文档。
要向 Pub/Sub 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证。
using Google.Cloud.PubSub.V1;
using System;
using System.IO;
public class CommitProtoSchemaSample
{
public Schema CommitProtoSchema(string projectId, string schemaId, string pathToNewDefinition)
{
SchemaServiceClient schemaService = SchemaServiceClient.Create();
var schemaName = SchemaName.FromProjectSchema(projectId, schemaId);
string schemaDefinition = File.ReadAllText(pathToNewDefinition);
Schema schema = new Schema
{
SchemaName = schemaName,
Type = Schema.Types.Type.ProtocolBuffer,
Definition = schemaDefinition
};
schema = schemaService.CommitSchema(schemaName, schema);
Console.WriteLine($"Schema {schema.Name} committed.");
return schema;
}
}
Go
试用此示例之前,请按照 Pub/Sub 快速入门:使用客户端库中的 Go 设置说明进行操作。如需了解详情,请参阅 Pub/Sub Go API 参考文档。
要向 Pub/Sub 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证。
import (
"context"
"fmt"
"io"
"io/ioutil"
"cloud.google.com/go/pubsub"
)
// commitProtoSchema commits a new proto schema revision to an existing schema.
func commitProtoSchema(w io.Writer, projectID, schemaID, protoFile string) error {
// projectID := "my-project-id"
// schemaID := "my-schema"
// protoFile = "path/to/a/proto/schema/file(.proto)/formatted/in/protocol/buffers"
ctx := context.Background()
client, err := pubsub.NewSchemaClient(ctx, projectID)
if err != nil {
return fmt.Errorf("pubsub.NewSchemaClient: %w", err)
}
defer client.Close()
// Read a proto file as a byte slice.
protoSource, err := ioutil.ReadFile(protoFile)
if err != nil {
return fmt.Errorf("error reading from file: %s", protoFile)
}
config := pubsub.SchemaConfig{
Name: fmt.Sprintf("projects/%s/schemas/%s", projectID, schemaID),
Type: pubsub.SchemaProtocolBuffer,
Definition: string(protoSource),
}
s, err := client.CommitSchema(ctx, schemaID, config)
if err != nil {
return fmt.Errorf("CommitSchema: %w", err)
}
fmt.Fprintf(w, "Committed a schema using a protobuf schema: %#v\n", s)
return nil
}
Java
试用此示例之前,请按照 Pub/Sub 快速入门:使用客户端库中的 Java 设置说明进行操作。如需了解详情,请参阅 Pub/Sub Java API 参考文档。
要向 Pub/Sub 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证。
import com.google.api.gax.rpc.NotFoundException;
import com.google.cloud.pubsub.v1.SchemaServiceClient;
import com.google.pubsub.v1.ProjectName;
import com.google.pubsub.v1.Schema;
import com.google.pubsub.v1.SchemaName;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public class CommitProtoSchemaExample {
public static void main(String... args) throws Exception {
// TODO(developer): Replace these variables before running the sample.
String projectId = "your-project-id";
String schemaId = "your-schema-id";
String protoFile = "path/to/a/proto/file/(.proto)/formatted/in/protocol/buffers";
commitProtoSchemaExample(projectId, schemaId, protoFile);
}
public static Schema commitProtoSchemaExample(String projectId, String schemaId, String protoFile)
throws IOException {
ProjectName projectName = ProjectName.of(projectId);
SchemaName schemaName = SchemaName.of(projectId, schemaId);
// Read a proto file as a string.
String protoSource = new String(Files.readAllBytes(Paths.get(protoFile)));
try (SchemaServiceClient schemaServiceClient = SchemaServiceClient.create()) {
Schema schema =
schemaServiceClient.commitSchema(
schemaName.toString(),
Schema.newBuilder()
.setName(schemaName.toString())
.setType(Schema.Type.PROTOCOL_BUFFER)
.setDefinition(protoSource)
.build());
System.out.println("Committed a schema using a protobuf schema:\n" + schema);
return schema;
} catch (NotFoundException e) {
System.out.println(schemaName + "does not exist.");
return null;
}
}
}
Node.js
/**
* TODO(developer): Uncomment these variables before running the sample.
*/
// const schemaNameOrId = 'YOUR_SCHEMA_NAME_OR_ID';
// const protoFile = 'path/to/a/proto/schema/file/(.proto)/formatted/in/protcol/buffers';
// Imports the Google Cloud client library
const {PubSub, SchemaTypes} = require('@google-cloud/pubsub');
const fs = require('fs');
// Creates a client; cache this for further use
const pubSubClient = new PubSub();
async function commitProtoSchema(schemaNameOrId, protoFile) {
// Get the fully qualified schema name.
const schema = pubSubClient.schema(schemaNameOrId);
const name = await schema.getName();
// Read the new schema definition from storage.
const definition = fs.readFileSync(protoFile).toString();
// Use the gapic client to commit the new definition.
const schemaClient = await pubSubClient.getSchemaClient();
const [result] = await schemaClient.commitSchema({
name,
schema: {
name,
type: SchemaTypes.ProtocolBuffer,
definition,
},
});
console.log(`Schema ${name} committed with revision ${result.revisionId}.`);
}
Node.js
/**
* TODO(developer): Uncomment these variables before running the sample.
*/
// const schemaNameOrId = 'YOUR_SCHEMA_NAME_OR_ID';
// const protoFile = 'path/to/a/proto/schema/file/(.proto)/formatted/in/protcol/buffers';
// Imports the Google Cloud client library
import {PubSub, SchemaTypes} from '@google-cloud/pubsub';
import * as fs from 'fs';
// Creates a client; cache this for further use
const pubSubClient = new PubSub();
async function commitProtoSchema(schemaNameOrId: string, protoFile: string) {
// Get the fully qualified schema name.
const schema = pubSubClient.schema(schemaNameOrId);
const name = await schema.getName();
// Read the new schema definition from storage.
const definition: string = fs.readFileSync(protoFile).toString();
// Use the gapic client to commit the new definition.
const schemaClient = await pubSubClient.getSchemaClient();
const [result] = await schemaClient.commitSchema({
name,
schema: {
name,
type: SchemaTypes.ProtocolBuffer,
definition,
},
});
console.log(`Schema ${name} committed with revision ${result.revisionId}.`);
}
PHP
试用此示例之前,请按照 Pub/Sub 快速入门:使用客户端库中的 PHP 设置说明进行操作。如需了解详情,请参阅 Pub/Sub PHP API 参考文档。
要向 Pub/Sub 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证。
use Google\Cloud\Core\Exception\NotFoundException;
use Google\Cloud\PubSub\PubSubClient;
/**
* Commit a new Proto schema revision to an existing schema.
*
* @param string $projectId The ID of your Google Cloud project.
* @param string $schemaId The ID of the schema to commit.
* @param string $protoFile The path to the Proto schema file.
* @return void
*/
function commit_proto_schema(string $projectId, string $schemaId, string $protoFile): void
{
$client = new PubSubClient([
'projectId' => $projectId
]);
try {
$schema = $client->schema($schemaId);
$definition = file_get_contents($protoFile);
$info = $schema->commit($definition, 'PROTOCOL_BUFFER');
printf("Committed a schema using a Protocol Buffer schema: %s\n", $info['name']);
} catch (NotFoundException $e) {
printf("%s does not exist.\n", $schemaId);
}
}
Python
试用此示例之前,请按照 Pub/Sub 快速入门:使用客户端库中的 Python 设置说明进行操作。如需了解详情,请参阅 Pub/Sub Python API 参考文档。
要向 Pub/Sub 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证。
from google.api_core.exceptions import NotFound
from google.cloud.pubsub import SchemaServiceClient
from google.pubsub_v1.types import Schema
# TODO(developer): Replace these variables before running the sample.
# project_id = "your-project-id"
# schema_id = "your-schema-id"
# proto_file = "path/to/a/proto/file/(.proto)/formatted/in/protocol/buffers"
# Read a protobuf schema file as a string.
with open(proto_file, "rb") as f:
proto_source = f.read().decode("utf-8")
schema_client = SchemaServiceClient()
schema_path = schema_client.schema_path(project_id, schema_id)
schema = Schema(
name=schema_path, type_=Schema.Type.PROTOCOL_BUFFER, definition=proto_source
)
try:
result = schema_client.commit_schema(
request={"schema": schema, "name": schema_path}
)
print(f"Committed a schema revision using a protobuf schema file:\n{result}")
return result
except NotFound:
print(f"{schema_id} does not exist.")
后续步骤
如需搜索和过滤其他 Google Cloud 产品的代码示例,请参阅 Google Cloud 示例浏览器。