使用协议缓冲区文件创建架构资源。
深入探索
如需查看包含此代码示例的详细文档,请参阅以下内容:
代码示例
C++
在尝试此示例之前,请按照使用客户端库的 Pub/Sub 快速入门中的 C++ 设置说明进行操作。如需了解详情,请参阅 Pub/Sub C++ API 参考文档。
namespace pubsub = ::google::cloud::pubsub;
[](pubsub::SchemaServiceClient client, std::string const& project_id,
std::string const& schema_id) {
auto constexpr kDefinition = R"pfile(
syntax = "proto3";
package google.cloud.pubsub.samples;
message State {
string name = 1;
string post_abbr = 2;
}
)pfile";
google::pubsub::v1::CreateSchemaRequest request;
request.set_parent(google::cloud::Project(project_id).FullName());
request.set_schema_id(schema_id);
request.mutable_schema()->set_type(
google::pubsub::v1::Schema::PROTOCOL_BUFFER);
request.mutable_schema()->set_definition(kDefinition);
auto schema = client.CreateSchema(request);
if (schema.status().code() == google::cloud::StatusCode::kAlreadyExists) {
std::cout << "The schema already exists\n";
return;
}
if (!schema) throw std::move(schema).status();
std::cout << "Schema successfully created: " << schema->DebugString()
<< "\n";
}
C#
在尝试此示例之前,请按照使用客户端库的 Pub/Sub 快速入门中的 C# 设置说明进行操作。如需了解详情,请参阅 Pub/Sub C# API 参考文档。
using Google.Cloud.PubSub.V1;
using Grpc.Core;
using System;
using System.IO;
public class CreateProtoSchemaSample
{
public Schema CreateProtoSchema(string projectId, string schemaId, string pathToDefinition)
{
SchemaServiceClient schemaService = SchemaServiceClient.Create();
var schemaName = SchemaName.FromProjectSchema(projectId, schemaId);
string schemaDefinition = File.ReadAllText(pathToDefinition);
Schema schema = new Schema
{
Name = schemaName.ToString(),
Type = Schema.Types.Type.ProtocolBuffer,
Definition = schemaDefinition
};
CreateSchemaRequest createSchemaRequest = new CreateSchemaRequest
{
Parent = "projects/" + projectId,
SchemaId = schemaId,
Schema = schema
};
try
{
schema = schemaService.CreateSchema(createSchemaRequest);
Console.WriteLine($"Schema {schema.Name} created.");
}
catch (RpcException e) when (e.Status.StatusCode == StatusCode.AlreadyExists)
{
Console.WriteLine($"Schema {schemaName} already exists.");
}
return schema;
}
}
Go
在尝试此示例之前,请按照使用客户端库的 Pub/Sub 快速入门中的 Go 设置说明进行操作。如需了解详情,请参阅 Pub/Sub Go API 参考文档。
import (
"context"
"fmt"
"io"
"os"
"cloud.google.com/go/pubsub"
)
// createProtoSchema creates a schema resource from a schema proto file.
func createProtoSchema(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: %v", err)
}
defer client.Close()
protoSource, err := os.ReadFile(protoFile)
if err != nil {
return fmt.Errorf("error reading from file: %s", protoFile)
}
config := pubsub.SchemaConfig{
Type: pubsub.SchemaProtocolBuffer,
Definition: string(protoSource),
}
s, err := client.CreateSchema(ctx, schemaID, config)
if err != nil {
return fmt.Errorf("CreateSchema: %v", err)
}
fmt.Fprintf(w, "Schema created: %#v\n", s)
return nil
}
Java
在尝试此示例之前,请按照使用客户端库的 Pub/Sub 快速入门中的 Java 设置说明进行操作。如需了解详情,请参阅 Pub/Sub Java API 参考文档。
import com.google.api.gax.rpc.AlreadyExistsException;
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 CreateProtoSchemaExample {
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";
createProtoSchemaExample(projectId, schemaId, protoFile);
}
public static Schema createProtoSchemaExample(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.createSchema(
projectName,
Schema.newBuilder()
.setName(schemaName.toString())
.setType(Schema.Type.PROTOCOL_BUFFER)
.setDefinition(protoSource)
.build(),
schemaId);
System.out.println("Created a schema using a protobuf schema:\n" + schema);
return schema;
} catch (AlreadyExistsException e) {
System.out.println(schemaName + "already exists.");
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 createProtoSchema(schemaNameOrId, protoFile) {
const definition = fs.readFileSync(protoFile).toString();
const schema = await pubSubClient.createSchema(
schemaNameOrId,
SchemaTypes.ProtocolBuffer,
definition
);
const fullName = await schema.getName();
console.log(`Schema ${fullName} created.`);
}
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 createProtoSchema(schemaNameOrId: string, protoFile: string) {
const definition: string = fs.readFileSync(protoFile).toString();
const schema = await pubSubClient.createSchema(
schemaNameOrId,
SchemaTypes.ProtocolBuffer,
definition
);
const fullName: string = await schema.getName();
console.log(`Schema ${fullName} created.`);
}
PHP
在尝试此示例之前,请按照使用客户端库的 Pub/Sub 快速入门中的 PHP 设置说明进行操作。如需了解详情,请参阅 Pub/Sub PHP API 参考文档。
use Google\Cloud\PubSub\PubSubClient;
use Google\Cloud\PubSub\V1\Schema\Type;
/**
* Create a Schema with an Protocol Buffer definition.
*
* @param string $projectId
* @param string $schemaId
* @param string $protoFile
*/
function create_proto_schema($projectId, $schemaId, $protoFile)
{
$pubsub = new PubSubClient([
'projectId' => $projectId,
]);
$definition = file_get_contents($protoFile);
$schema = $pubsub->createSchema($schemaId, Type::PROTOCOL_BUFFER, $definition);
printf('Schema %s created.', $schema->name());
}
Python
在尝试此示例之前,请按照使用客户端库的 Pub/Sub 快速入门中的 Python 设置说明进行操作。如需了解详情,请参阅 Pub/Sub Python API 参考文档。
from google.api_core.exceptions import AlreadyExists
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"
project_path = f"projects/{project_id}"
# 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.create_schema(
request={"parent": project_path, "schema": schema, "schema_id": schema_id}
)
print(f"Created a schema using a protobuf schema file:\n{result}")
return result
except AlreadyExists:
print(f"{schema_id} already exists.")
Ruby
在尝试此示例之前,请按照使用客户端库的 Pub/Sub 快速入门中的 Ruby 设置说明进行操作。如需了解详情,请参阅 Pub/Sub Ruby API 参考文档。
# schema_id = "your-schema-id"
# proto_file = "path/to/a/proto/file/(.proto)/formatted/in/protocol/buffers"
require "google/cloud/pubsub"
pubsub = Google::Cloud::Pubsub.new
definition = File.read proto_file
schema = pubsub.create_schema schema_id, :protocol_buffer, definition
puts "Schema #{schema.name} created."
后续步骤
如需搜索和过滤其他 Google Cloud 产品的代码示例,请参阅 Google Cloud 示例浏览器。