查看結構定義的詳細資料

本文說明如何查看 Pub/Sub 主題的結構定義詳細資料。

事前準備

必要角色和權限

如要取得查看及管理結構定義詳細資料所需的權限,請要求管理員授予專案的「Pub/Sub 編輯者」 (roles/pubsub.editor) IAM 角色。如要進一步瞭解如何授予角色,請參閱「管理專案、資料夾和機構的存取權」。

這個預先定義的角色具備查看及管理結構定義詳細資料所需的權限。如要查看確切的必要權限,請展開「必要權限」部分:

所需權限

如要查看及管理結構定義詳細資料,必須具備下列權限:

  • 建立結構定義: pubsub.schemas.create
  • 將結構定義附加至主題: pubsub.schemas.attach
  • 提交結構定義修訂版本: pubsub.schemas.commit
  • 刪除結構定義或結構定義修訂版本: pubsub.schemas.delete
  • 取得結構定義或結構定義修訂版本: pubsub.schemas.get
  • 列出結構定義: pubsub.schemas.list
  • 列出結構定義修訂版本: pubsub.schemas.listRevisions
  • 回溯結構定義: pubsub.schemas.rollback
  • 驗證訊息: pubsub.schemas.validate
  • 取得結構定義的身分與存取權管理政策: pubsub.schemas.getIamPolicy
  • 設定結構定義的 IAM 政策 pubsub.schemas.setIamPolicy

您或許還可透過自訂角色或其他預先定義的角色取得這些權限。

您可以將角色和權限授予主體,例如使用者、群組、網域或服務帳戶。您可以在一個專案中建立結構定義,並將其附加至位於其他專案的主題。請確認您具備每個專案的必要權限。

查看結構定義詳細資料

您可以使用Trusted Cloud 控制台、gcloud CLI、Pub/Sub API 或 Cloud 用戶端程式庫,取得結構定義的詳細資料。結果會傳回最新修訂 ID 的詳細資料。

控制台

  1. 前往 Trusted Cloud 控制台的「Pub/Sub schemas」(Pub/Sub 結構定義) 頁面。

    前往「結構定義」

  2. 按一下要查看的結構定義名稱。

    系統會開啟結構定義的「結構定義詳細資料」頁面。

gcloud

如要查看結構定義的最新修訂版本:

gcloud pubsub schemas describe SCHEMA_NAME

如要查看特定結構定義的修訂版本:

gcloud pubsub schemas describe SCHEMA_ID@REVISION_ID

其中:

  • REVISION_ID 是要復原的修訂版本。

REST

如要取得最新修訂版本的結構定義詳細資料,請傳送類似下列的 GET 要求:

GET https://pubsub.googleapis.com/v1/projects/PROJECT_ID/schemas/SCHEMA_ID

舉例來說,如要取得結構定義 ID 為 schema-inventory 的結構定義,請傳送下列要求:https://pubsub.googleapis.com/v1/projects/PROJECT_ID/schemas/schema-inventory

如要取得特定結構定義修訂版本的詳細資料,請傳送類似下列的 GET 要求:

GET https://pubsub.googleapis.com/v1/projects/PROJECT_ID/schemas/SCHEMA_ID@REVISION_ID

舉例來說,如要取得架構 ID 為 schema-inventory 且修訂版本 ID 為 fa567a3e 的架構,請傳送下列要求:https://pubsub.googleapis.com/v1/projects/PROJECT_ID/schemas/schema-inventory@fa567a3e

其中:

  • PROJECT_ID 是您的專案 ID。
  • SCHEMA_ID 是結構定義 ID。
  • REVISION_ID 是特定結構定義的修訂版本 ID。

如果成功,回應主體會包含結構定義類別的執行個體。

C++

在試用這個範例之前,請先按照快速入門:使用用戶端程式庫中的 C++ 設定操作說明進行操作。詳情請參閱 Pub/Sub C++ API 參考說明文件

namespace pubsub = ::google::cloud::pubsub;
[](pubsub::SchemaServiceClient client, std::string const& project_id,
   std::string const& schema_id, std::string const& revision_id) {
  std::string const schema_id_with_revision = schema_id + "@" + revision_id;

  google::pubsub::v1::GetSchemaRequest request;
  request.set_name(
      pubsub::Schema(project_id, schema_id_with_revision).FullName());
  request.set_view(google::pubsub::v1::FULL);
  auto schema = client.GetSchema(request);
  if (!schema) throw std::move(schema).status();

  std::cout << "The schema revision exists and its metadata is:"
            << "\n"
            << schema->DebugString() << "\n";
}

C#

在嘗試這個範例之前,請先按照快速入門:使用用戶端程式庫中的 C# 設定操作說明進行操作。詳情請參閱 Pub/Sub C# API 參考說明文件


using Google.Cloud.PubSub.V1;

public class GetSchemaSample
{
    public Schema GetSchema(string projectId, string schemaId)
    {
        SchemaServiceClient schemaService = SchemaServiceClient.Create();
        GetSchemaRequest request = new GetSchemaRequest
        {
            SchemaName = SchemaName.FromProjectSchema(projectId, schemaId),
            View = SchemaView.Full
        };

        return schemaService.GetSchema(request);
    }
}

Go

以下範例使用 Go Pub/Sub 用戶端程式庫的主要版本 (v2)。如果您仍在使用第 1 版程式庫,請參閱第 2 版遷移指南。如要查看第 1 版程式碼範例清單,請參閱 已淘汰的程式碼範例

在試用這個範例之前,請先按照快速入門:使用用戶端程式庫中的 Go 設定說明進行操作。詳情請參閱 Pub/Sub Go API 參考說明文件

import (
	"context"
	"fmt"
	"io"

	pubsub "cloud.google.com/go/pubsub/v2/apiv1"
	"cloud.google.com/go/pubsub/v2/apiv1/pubsubpb"
)

func getSchemaRevision(w io.Writer, projectID, schemaID string) error {
	// projectID := "my-project-id"
	// schemaID := my-schema@c7cfa2a8 // with revision
	ctx := context.Background()
	client, err := pubsub.NewSchemaClient(ctx)
	if err != nil {
		return fmt.Errorf("pubsub.NewSchemaClient: %w", err)
	}
	defer client.Close()

	req := &pubsubpb.GetSchemaRequest{
		Name: fmt.Sprintf("projects/%s/schemas/%s", projectID, schemaID),
		View: pubsubpb.SchemaView_FULL,
	}
	s, err := client.GetSchema(ctx, req)
	if err != nil {
		return fmt.Errorf("client.GetSchema revision: %w", err)
	}
	fmt.Fprintf(w, "Got schema revision: %#v\n", s)
	return nil
}

Java

在試用這個範例之前,請先按照快速入門:使用用戶端程式庫中的 Java 設定操作說明進行操作。詳情請參閱 Pub/Sub Java API 參考說明文件


import com.google.api.gax.rpc.NotFoundException;
import com.google.cloud.pubsub.v1.SchemaServiceClient;
import com.google.pubsub.v1.Schema;
import com.google.pubsub.v1.SchemaName;
import java.io.IOException;

public class GetSchemaRevisionExample {

  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[@your-schema-revision]";
    getSchemaRevisionExample(projectId, schemaId);
  }

  public static void getSchemaRevisionExample(String projectId, String schemaId)
      throws IOException {
    SchemaName schemaName = SchemaName.of(projectId, schemaId);

    try (SchemaServiceClient schemaServiceClient = SchemaServiceClient.create()) {

      Schema schema = schemaServiceClient.getSchema(schemaName);

      System.out.println("Got a schema:\n" + schema);

    } catch (NotFoundException e) {
      System.out.println(schemaName + "not found.");
    }
  }
}

Node.js

在嘗試這個範例之前,請先按照快速入門:使用用戶端程式庫中的 Node.js 設定說明進行操作。詳情請參閱 Pub/Sub Node.js API 參考說明文件

/**
 * TODO(developer): Uncomment this variable before running the sample.
 */
// const schemaNameOrId = 'YOUR_SCHEMA_NAME_OR_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 getSchema(schemaNameOrId) {
  const schema = pubSubClient.schema(schemaNameOrId);
  const info = await schema.get();
  const fullName = await schema.getName();
  console.log(`Schema ${fullName} info: ${JSON.stringify(info, null, 4)}.`);
}

Node.js

在嘗試這個範例之前,請先按照快速入門:使用用戶端程式庫中的 Node.js 設定說明進行操作。詳情請參閱 Pub/Sub Node.js API 參考說明文件

/**
 * TODO(developer): Uncomment this variable before running the sample.
 */
// const schemaNameOrId = 'YOUR_SCHEMA_NAME_OR_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 getSchema(schemaNameOrId: string) {
  const schema = pubSubClient.schema(schemaNameOrId);
  const info = await schema.get();
  const fullName = await schema.getName();
  console.log(`Schema ${fullName} info: ${JSON.stringify(info, null, 4)}.`);
}

PHP

在試用這個範例之前,請先按照快速入門:使用用戶端程式庫中的 PHP 設定說明進行操作。 詳情請參閱 Pub/Sub PHP API 參考說明文件

use Google\Cloud\PubSub\PubSubClient;

/**
 * Get a schema.
 *
 * @param string $projectId
 * @param string $schemaId
 */
function get_schema($projectId, $schemaId)
{
    $pubsub = new PubSubClient([
        'projectId' => $projectId,
    ]);

    $schema = $pubsub->schema($schemaId);
    $schema->info();

    printf('Schema %s retrieved', $schema->name());
}

Python

在試用這個範例之前,請先按照快速入門:使用用戶端程式庫中的 Python 設定操作說明來進行。詳情請參閱 Pub/Sub Python API 參考說明文件

from google.api_core.exceptions import NotFound
from google.cloud.pubsub import SchemaServiceClient

# TODO(developer): Replace these variables before running the sample.
# project_id = "your-project-id"
# schema_id = "your-schema-id"
# schema_revision_id = "your-schema-revision-id"

schema_client = SchemaServiceClient()
schema_path = schema_client.schema_path(
    project_id, schema_id + "@" + schema_revision_id
)

try:
    result = schema_client.get_schema(request={"name": schema_path})
    print(f"Got a schema revision:\n{result}")
except NotFound:
    print(f"{schema_id} not found.")

Ruby

以下範例使用 Ruby Pub/Sub 用戶端程式庫 v3。如果您仍在使用第 2 版程式庫,請參閱 第 3 版遷移指南。如要查看 Ruby 第 2 版程式碼範例清單,請參閱 已淘汰的程式碼範例

在試用這個範例之前,請先按照快速入門:使用用戶端程式庫的操作說明設定 Ruby 環境。詳情請參閱 Pub/Sub Ruby API 參考說明文件

# schema_id = "your-schema-id"

pubsub = Google::Cloud::PubSub.new
schemas = pubsub.schemas

schema = schemas.get_schema name: pubsub.schema_path(schema_id)

puts "Schema #{schema.name} retrieved."

後續步驟