스키마를 주제와 연결

이 문서에서는 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
  • 스키마의 IAM 정책 가져오기: pubsub.schemas.getIamPolicy
  • 스키마의 IAM 정책 구성: pubsub.schemas.setIamPolicy

커스텀 역할이나 다른 사전 정의된 역할을 사용하여 이 권한을 부여받을 수도 있습니다.

사용자, 그룹, 도메인, 서비스 계정과 같은 주 구성원에 역할 및 권한을 부여할 수 있습니다. 한 프로젝트에서 스키마를 만들고 이를 다른 프로젝트에 있는 주제에 연결할 수 있습니다. 각 프로젝트에 필요한 권한이 있는지 확인합니다.

스키마를 주제와 연결하는 방법 가이드라인

주제를 만들거나 편집할 때 스키마를 주제와 연결할 수 있습니다. 다음은 스키마를 주제와 연결하기 위한 가이드라인입니다.

  • 스키마를 하나 이상의 주제와 연결할 수 있습니다.

    스키마가 주제와 연결된 다음에는 주제가 게시자에서 수신하는 모든 메시지가 해당 스키마를 따라야 합니다.

  • 또한 스키마를 주제와 연결할 때는 게시할 메시지 인코딩을 BINARY 또는 JSON으로 지정해야 합니다. Avro 스키마에서 JSON을 사용하는 경우 union에 대한 인코딩 규칙에 주의하세요.

  • 주제와 연결된 스키마에 여러 버전이 포함된 경우 메시지가 인코딩과 일치해야 하고 사용 가능한 범위 내의 버전에 대해 유효한지 검사해야 합니다. 유효하지 않으면 메시지가 게시되지 않습니다.

    버전은 생성 시간의 역순으로 시도됩니다. 스키마 버전을 만들려면 스키마 버전 커밋을 참조하세요.

메시지 스키마의 유효성 검사 논리

스키마를 주제와 연결할 때 스키마에 여러 버전이 포함되어 있으면 사용할 버전의 하위 집합 범위를 지정할 수 있습니다. 범위를 지정하지 않으면 전체 범위가 유효성 검사에 사용됩니다.

특정 버전을 허용된 첫 번째 버전으로 지정하지 않으면 스키마에서 가장 오래된 기존 버전이 유효성 검사에 사용됩니다. 특정 버전을 허용된 마지막 버전으로 지정하지 않으면 스키마에서 가장 새로운 기존 버전이 사용됩니다.

예를 들어 T 주제에 연결된 S 스키마가 있다고 가정해보세요.

S 스키마에는 순서대로 A, B, C, D에 해당하는 버전 ID가 있고, A가 첫 번째 버전 또는 가장 오래된 버전입니다. 스키마는 서로 동일하지 않고 기존 스키마의 롤백이 아닙니다.

  • 허용된 첫 번째 버전 필드를 B로만 설정할 경우에는 A 스키마와 호환되는 메시지만 거부되고 B, C, D 스키마와 호환되는 메시지는 허용됩니다.

  • 허용된 마지막 버전 필드를 C로만 설정할 경우에는 A, B, C 스키마와 호환되는 메시지가 허용되고 D 스키마와 호환되는 메시지만 거부됩니다.

  • 허용된 첫 번째 버전 필드를 B로 설정하고 허용된 마지막 버전 필드를 C로 설정하면 BC 스키마와 호환되는 메시지가 허용됩니다.

  • 또한 첫 번째 버전과 마지막 버전을 동일한 버전 ID로 설정할 수도 있습니다. 이 경우 해당 버전과 호환되는 메시지만 허용됩니다.

주제를 만들 때 스키마 만들기 및 연결

Google Cloud 콘솔, gcloud CLI, Pub/Sub API, Cloud 클라이언트 라이브러리를 사용하여 주제를 스키마와 연결할 수 있습니다.

콘솔

  1. Google Cloud 콘솔에서 Pub/Sub 주제 페이지로 이동합니다.

    주제로 이동

  2. 주제 만들기를 클릭합니다.

  3. 주제 ID 필드에 주제의 ID를 입력합니다.

    주제 이름을 지정하려면 가이드라인을 참조하세요.

  4. 스키마 사용 체크박스를 선택합니다.

    나머지 필드는 기본 설정을 그대로 둡니다.

    스키마를 만들거나 기존 스키마를 사용할 수 있습니다.

  5. 스키마를 만들려면 다음 단계를 수행합니다.

    1. Pub/Sub 스키마 선택에 대해 새 스키마 만들기를 선택합니다.

    스키마 만들기 페이지가 보조 탭에 표시됩니다.

    스키마 만들기의 단계를 수행합니다.

    1. 주제 만들기 탭으로 이동하고 새로고침을 클릭합니다.

    2. Pub/Sub 스키마 선택 필드에서 스키마를 검색합니다.

    3. 메시지 인코딩을 JSON 또는 바이너리로 선택합니다.

    방금 만든 스키마에 버전 ID가 포함됩니다. 스키마 버전 커밋에 설명된 대로 추가 스키마 버전을 만들 수 있습니다.

  6. 이미 생성된 스키마를 연결하는 경우 다음 단계를 수행합니다.

    1. Pub/Sub 스키마 선택에 대해 기존 스키마를 선택합니다.

    2. 메시지 인코딩을 JSON 또는 바이너리로 선택합니다.

  7. 선택사항: 선택한 스키마에 버전이 포함된 경우 버전 범위에 대해 허용된 첫 번째 버전허용된 마지막 버전의 드롭다운 메뉴를 사용합니다.

요구사항에 따라 두 필드를 모두 지정하거나, 하나만 지정하거나, 기본 설정을 그대로 둘 수 있습니다.

  1. 나머지 필드는 기본 설정을 그대로 둡니다.

  2. 만들기를 클릭하여 주제를 저장하고 선택한 스키마에 할당합니다.

gcloud

이전에 만든 스키마로 할당된 주제를 만들려면 gcloud pubsub topics create 명령어를 실행합니다.

gcloud pubsub topics create TOPIC_ID \
        --message-encoding=ENCODING_TYPE \
        --schema=SCHEMA_ID \
        --first-revision-id=FIRST_REVISION_ID \
        --last-revision-id=LAST_REVISION_ID \

각 항목의 의미는 다음과 같습니다.

  • TOPIC_ID는 만들려는 주제의 ID입니다.
  • ENCODING_TYPE은 스키마에 대해 검증된 메시지의 인코딩 유형입니다. 이 값은 JSON 또는 BINARY로 설정해야 합니다.
  • SCHEMA_ID는 기존 스키마의 ID입니다.
  • FIRST_REVISION_ID는 유효성을 검사할 가장 오래된 버전의 ID입니다.
  • LAST_REVISION_ID는 유효성을 검사할 최신 버전의 ID입니다.

--first-revision-id--last-revision-id 모두 선택사항입니다.

다른 Google Cloud 프로젝트의 스키마를 할당할 수도 있습니다.

gcloud pubsub topics create TOPIC_ID \
        --message-encoding=ENCODING_TYPE \
        --schema=SCHEMA_ID \
        --schema-project=SCHEMA_PROJECT \
        --project=TOPIC_PROJECT

각 항목의 의미는 다음과 같습니다.

  • SCHEMA_PROJECT는 스키마에 대한 Google Cloud 프로젝트의 프로젝트 ID입니다.
  • TOPIC_PROJECT는 주제에 대한 Google Cloud 프로젝트의 프로젝트 ID입니다.

REST

주제를 만들려면 projects.topics.create 메서드를 사용합니다.

요청:

요청은 Authorization 헤더의 액세스 토큰으로 인증해야 합니다. 현재 애플리케이션 기본 사용자 인증 정보에 대한 액세스 토큰을 얻는 방법은 다음과 같습니다. gcloud auth application-default print-access-token.

PUT https://pubsub.googleapis.com/v1/projects/PROJECT_ID/topics/TOPIC_ID
Authorization: Bearer ACCESS_TOKEN

요청 본문:

{
  "schemaSettings": {
    "schema": "SCHEMA_NAME",
    "encoding": "ENCODING_TYPE"
    "firstRevisionId": "FIRST_REVISION_ID"
    "lastRevisionId": "LAST_REVISION_ID"
  }
}

각 항목의 의미는 다음과 같습니다.

  • PROJECT_ID는 프로젝트 ID입니다.
  • TOPIC_ID는 주제 ID입니다.
  • SCHEMA_NAME은 게시된 메시지를 검증할 대상인 스키마의 이름입니다. 형식은 projects/PROJECT_ID/schemas/SCHEMA_ID입니다.
  • ENCODING_TYPE은 스키마에 대해 검증된 메시지의 인코딩 유형입니다. JSON 또는 BINARY로 설정되어야 합니다.
  • FIRST_REVISION_ID는 유효성을 검사할 가장 오래된 버전의 ID입니다.
  • LAST_REVISION_ID는 유효성을 검사할 최신 버전의 ID입니다.

firstRevisionIdlastRevisionId 모두 선택사항입니다.

응답:

{
  "name": "projects/PROJECT_ID/topics/TOPIC_ID",
  "schemaSettings": {
    "schema": "SCHEMA_NAME",
    "encoding": "ENCODING_TYPE"
    "firstRevisionId": "FIRST_REVISION_ID"
    "lastRevisionId": "LAST_REVISION_ID"
  }
}

요청에 제공되지 않은 경우 firstRevisionIdlastRevisionId가 모두 생략됩니다.

C++

이 샘플을 시도하기 전에 빠른 시작: 클라이언트 라이브러리 사용의 C++ 설정 안내를 따르세요. 자세한 내용은 Pub/Sub C++ API 참고 문서를 확인하세요.

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) {
  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);
  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#

이 샘플을 시도하기 전에 빠른 시작: 클라이언트 라이브러리 사용의 C# 설정 안내를 따르세요. 자세한 내용은 Pub/Sub C# API 참고 문서를 확인하세요.


using Google.Cloud.PubSub.V1;
using Grpc.Core;
using System;

public class CreateTopicWithSchemaSample
{
    public Topic CreateTopicWithSchema(string projectId, string topicId, string schemaId, 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),
                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

이 샘플을 시도하기 전에 빠른 시작: 클라이언트 라이브러리 사용의 Go 설정 안내를 따르세요. 자세한 내용은 Pub/Sub Go API 참고 문서를 참조하세요.

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 API 참고 문서를 참조하세요.


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

이 샘플을 시도하기 전에 빠른 시작: 클라이언트 라이브러리 사용의 Node.js 설정 안내를 따르세요. 자세한 내용은 Pub/Sub Node.js API 참고 문서를 참조하세요.

/**
 * 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';

// 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 createTopicWithSchema(
  topicNameOrId,
  schemaNameOrId,
  encodingType
) {
  // 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,
    },
  });
  console.log(`Topic ${topicNameOrId} created with schema ${fullName}.`);
}

Node.js

이 샘플을 시도하기 전에 빠른 시작: 클라이언트 라이브러리 사용의 Node.js 설정 안내를 따르세요. 자세한 내용은 Pub/Sub Node.js API 참고 문서를 참조하세요.

/**
 * 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';

// 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 createTopicWithSchema(
  topicNameOrId: string,
  schemaNameOrId: string,
  encodingType: 'BINARY' | 'JSON'
) {
  // 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,
    },
  });
  console.log(`Topic ${topicNameOrId} created with schema ${fullName}.`);
}

PHP

이 샘플을 시도하기 전에 빠른 시작: 클라이언트 라이브러리 사용의 PHP 설정 안내를 따르세요. 자세한 내용은 Pub/Sub PHP API 참고 문서를 참조하세요.

use Google\Cloud\PubSub\PubSubClient;
use Google\Cloud\PubSub\Schema;

/**
 * Create a topic with a schema.
 *
 * @param string $projectId
 * @param string $topicId
 * @param string $schemaId
 * @param string $encoding
 */
function create_topic_with_schema($projectId, $topicId, $schemaId, $encoding)
{
    $pubsub = new PubSubClient([
        'projectId' => $projectId,
    ]);

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

    $topic = $pubsub->createTopic($topicId, [
        'schemaSettings' => [
            // The schema may be provided as an instance of the schema type,
            // or by using the schema ID directly.
            'schema' => $schema,
            // Encoding may be either `BINARY` or `JSON`.
            // Provide a string or a constant from Google\Cloud\PubSub\V1\Encoding.
            'encoding' => $encoding,
        ]
    ]);

    printf('Topic %s created', $topic->name());
}

Python

이 샘플을 시도하기 전에 빠른 시작: 클라이언트 라이브러리 사용의 Python 설정 안내를 따르세요. 자세한 내용은 Pub/Sub Python API 참고 문서를 참조하세요.

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.")

Ruby

이 샘플을 시도하기 전에 빠른 시작: 클라이언트 라이브러리 사용의 Ruby 설정 안내를 따르세요. 자세한 내용은 Pub/Sub Ruby API 참고 문서를 참조하세요.

# topic_id = "your-topic-id"
# schema_id = "your-schema-id"
# Choose either BINARY or JSON as valid message encoding in this topic.
# message_encoding = :binary

pubsub = Google::Cloud::Pubsub.new

topic = pubsub.create_topic topic_id, schema_name: schema_id, message_encoding: message_encoding

puts "Topic #{topic.name} created."

주제와 연결된 스키마 수정

스키마 연결, 스키마 삭제, 메시지 유효성 검사에 사용되는 버전 범위 업데이트를 위해 주제를 수정할 수 있습니다. 일반적으로 사용 중인 스키마에 대해 계획된 변경사항이 있으면 새 버전을 커밋하고 주제에 사용되는 버전 범위를 업데이트할 수 있습니다.

Google Cloud 콘솔, gcloud CLI, Pub/Sub API, Cloud 클라이언트 라이브러리를 사용하여 주제와 연결된 스키마를 수정할 수 있습니다.

콘솔

  1. Google Cloud 콘솔에서 Pub/Sub 주제 페이지로 이동합니다.

    주제로 이동

  2. 주제의 주제 ID를 클릭합니다.

  3. 주제 세부정보 페이지에서 수정을 클릭합니다.

  4. 스키마를 다음과 같이 변경할 수 있습니다.

    변경사항이 적용되려면 몇 분 정도 걸릴 수 있습니다.

    • 주제에서 스키마를 삭제하려면 주제 수정 페이지에서 스키마 사용 체크박스를 선택 해제합니다.

    • 스키마를 변경하려면 스키마 섹션에서 스키마 이름을 선택합니다.

    필요에 따라 다른 필드를 업데이트합니다.

    • 버전 범위를 업데이트하려면 버전 범위에 대해 허용된 첫 번째 버전허용된 마지막 버전의 드롭다운 메뉴를 사용합니다.

    요구사항에 따라 두 필드를 모두 지정하거나, 하나만 지정하거나, 기본 설정을 그대로 둘 수 있습니다.

  5. 업데이트를 클릭하여 변경사항을 저장합니다.

gcloud

gcloud pubsub topics update TOPIC_ID \
        --message-encoding=ENCODING_TYPE \
        --schema=SCHEMA_NAME \
        --first-revision-id=FIRST_REVISION_ID \
        --last-revision-id=LAST_REVISION_ID \

각 항목의 의미는 다음과 같습니다.

  • TOPIC_ID는 만들려는 주제의 ID입니다.
  • ENCODING_TYPE은 스키마에 대해 검증된 메시지의 인코딩 유형입니다. 이 값은 JSON 또는 BINARY로 설정해야 합니다.
  • SCHEMA_NAME은 기존 스키마 이름입니다.
  • FIRST_REVISION_ID는 유효성을 검사할 가장 오래된 버전의 ID입니다.
  • LAST_REVISION_ID는 유효성을 검사할 최신 버전의 ID입니다.

--first-revision-id--last-revision-id 모두 선택사항입니다.

REST

주제를 업데이트하려면 projects.topics.patch 메서드를 사용합니다.

요청:

요청은 Authorization 헤더의 액세스 토큰으로 인증해야 합니다. 현재 애플리케이션 기본 사용자 인증 정보에 대한 액세스 토큰을 얻는 방법은 다음과 같습니다. gcloud auth application-default print-access-token.

PATCH https://pubsub.googleapis.com/v1/projects/PROJECT_ID/topics/TOPIC_ID
Authorization: Bearer ACCESS_TOKEN

요청 본문:

{
  "schemaSettings": {
    "schema": "SCHEMA_NAME",
    "encoding": "ENCODING_TYPE"
    "firstRevisionId": "FIRST_REVISION_ID"
    "lastRevisionId": "LAST_REVISION_ID"
    "update_mask":
  }
}

각 항목의 의미는 다음과 같습니다.

  • PROJECT_ID는 프로젝트 ID입니다.
  • TOPIC_ID는 주제 ID입니다.
  • SCHEMA_NAME은 게시된 메시지를 검증할 대상인 스키마의 이름입니다. 형식은 projects/PROJECT_ID/schemas/SCHEMA_ID입니다.
  • ENCODING_TYPE은 스키마에 대해 검증된 메시지의 인코딩 유형입니다. JSON 또는 BINARY로 설정되어야 합니다.
  • FIRST_REVISION_ID는 유효성을 검사할 가장 오래된 버전의 ID입니다.
  • LAST_REVISION_ID는 유효성을 검사할 최신 버전의 ID입니다.

firstRevisionIdlastRevisionId 모두 선택사항입니다.

응답:

{
  "name": "projects/PROJECT_ID/topics/TOPIC_ID",
  "schemaSettings": {
    "schema": "SCHEMA_NAME",
    "encoding": "ENCODING_TYPE"
    "firstRevisionId": "FIRST_REVISION_ID"
    "lastRevisionId": "LAST_REVISION_ID"
  }
}

firstRevisionIdlastRevisionId 모두 업데이트 후에는 설정되지 않습니다.

C++

이 샘플을 시도하기 전에 빠른 시작: 클라이언트 라이브러리 사용의 C++ 설정 안내를 따르세요. 자세한 내용은 Pub/Sub C++ API 참고 문서를 확인하세요.

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";
}

Go

이 샘플을 시도하기 전에 빠른 시작: 클라이언트 라이브러리 사용의 Go 설정 안내를 따르세요. 자세한 내용은 Pub/Sub Go API 참고 문서를 참조하세요.

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 API 참고 문서를 참조하세요.


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());
    }
  }
}

Python

이 샘플을 시도하기 전에 빠른 시작: 클라이언트 라이브러리 사용의 Python 설정 안내를 따르세요. 자세한 내용은 Pub/Sub Python API 참고 문서를 참조하세요.

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.")
0

다음 단계