Listar as revisões de um esquema

Listar as revisões de um esquema

Mais informações

Para ver a documentação detalhada que inclui este exemplo de código, consulte:

Exemplo de código

C++

Antes de testar esta amostra, siga as instruções de configuração de C++ no Guia de início rápido do Pub/Sub usando bibliotecas de cliente. Para mais informações, consulte a documentação de referência da API Pub/Sub C++.

Para se autenticar no Pub/Sub, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

namespace pubsub = ::google::cloud::pubsub;
[](pubsub::SchemaServiceClient client, std::string const& project_id,
   std::string const& schema_id) {
  auto const parent = pubsub::Schema(project_id, schema_id).FullName();
  for (auto& s : client.ListSchemaRevisions(parent)) {
    if (!s) throw std::move(s).status();
    std::cout << "Schema revision: " << s->DebugString() << "\n";
  }
}

C#

Antes de testar esta amostra, siga as instruções de configuração de C# no Guia de início rápido do Pub/Sub usando bibliotecas de cliente. Para mais informações, consulte a documentação de referência da API Pub/Sub C#.

Para se autenticar no Pub/Sub, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.


using Google.Api.Gax.ResourceNames;
using Google.Cloud.PubSub.V1;
using System.Collections.Generic;
using System.Linq;

public class ListSchemaRevisionsSample
{
    public IEnumerable<Schema> ListSchemaRevisions(string projectId, string schemaId)
    {
        SchemaServiceClient schemaService = SchemaServiceClient.Create();
        SchemaName schemaName = SchemaName.FromProjectSchema(projectId, schemaId);
        return schemaService.ListSchemaRevisions(schemaName).ToList();
    }
}

Go

Antes de testar esta amostra, siga as instruções de configuração de Go no Guia de início rápido do Pub/Sub usando bibliotecas de cliente. Para mais informações, consulte a documentação de referência da API Pub/Sub Go.

Para se autenticar no Pub/Sub, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

import (
	"context"
	"fmt"
	"io"

	"cloud.google.com/go/pubsub"
	"google.golang.org/api/iterator"
)

func listSchemaRevisions(w io.Writer, projectID, schemaID string) ([]*pubsub.SchemaConfig, error) {
	// projectID := "my-project-id"
	// schemaID := "my-schema-id"
	ctx := context.Background()
	client, err := pubsub.NewSchemaClient(ctx, projectID)
	if err != nil {
		return nil, fmt.Errorf("pubsub.NewSchemaClient: %w", err)
	}
	defer client.Close()

	var schemas []*pubsub.SchemaConfig

	schemaIter := client.ListSchemaRevisions(ctx, schemaID, pubsub.SchemaViewFull)
	for {
		sc, err := schemaIter.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return nil, fmt.Errorf("schemaIter.Next: %w", err)
		}
		fmt.Fprintf(w, "Got schema revision: %#v\n", sc)
		schemas = append(schemas, sc)
	}

	fmt.Fprintf(w, "Got %d schema revisions", len(schemas))
	return schemas, nil
}

Java

Antes de testar esta amostra, siga as instruções de configuração de Java no Guia de início rápido do Pub/Sub usando bibliotecas de cliente. Para mais informações, consulte a documentação de referência da API Pub/Sub Java.

Para se autenticar no Pub/Sub, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

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 ListSchemaRevisionsExample {
  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";

    listSchemaRevisionsExample(projectId, schemaId);
  }

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

    try (SchemaServiceClient schemaServiceClient = SchemaServiceClient.create()) {
      for (Schema schema : schemaServiceClient.listSchemaRevisions(schemaName).iterateAll()) {
        System.out.println(schema);
      }
      System.out.println("Listed schema revisions.");
    }
  }
}

Node.js

/**
 * 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 listSchemaRevisions(schemaNameOrId) {
  // Get the fully qualified schema name.
  const schema = pubSubClient.schema(schemaNameOrId);
  const name = await schema.getName();

  // Use the gapic client to list the schema revisions.
  const schemaClient = await pubSubClient.getSchemaClient();
  const [results] = await schemaClient.listSchemaRevisions({
    name,
  });
  for (const rev of results) {
    console.log(rev.revisionId, rev.revisionCreateTime);
  }
  console.log(`Listed revisions of schema ${name}.`);
}

Node.js

/**
 * 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 listSchemaRevisions(schemaNameOrId: string) {
  // Get the fully qualified schema name.
  const schema = pubSubClient.schema(schemaNameOrId);
  const name = await schema.getName();

  // Use the gapic client to list the schema revisions.
  const schemaClient = await pubSubClient.getSchemaClient();
  const [results] = await schemaClient.listSchemaRevisions({
    name,
  });
  for (const rev of results) {
    console.log(rev.revisionId, rev.revisionCreateTime);
  }
  console.log(`Listed revisions of schema ${name}.`);
}

PHP

Antes de testar esta amostra, siga as instruções de configuração de PHP no Guia de início rápido do Pub/Sub usando bibliotecas de cliente. Para mais informações, consulte a documentação de referência da API Pub/Sub PHP.

Para se autenticar no Pub/Sub, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.


/**
 * Lists all schema revisions for the named schema.
 *
 * @param string $projectId The ID of your Google Cloud Platform project.
 * @param string $schemaId The ID of the schema.
 * @return void $name
 */
function list_schema_revisions(string $projectId, string $schemaId): void
{
    $client = new PubSubClient([
        'projectId' => $projectId
    ]);

    try {
        $schema = $client->schema($schemaId);
        $revisions = $schema->listRevisions();
        foreach ($revisions['schemas'] as $revision) {
            printf('Got a schema revision: %s' . PHP_EOL, $revision['revisionId']);
        }
        print('Listed schema revisions.' . PHP_EOL);
    } catch (NotFoundException $ex) {
        printf('%s not found' . PHP_EOL, $schemaId);
    }
}

Python

Antes de testar esta amostra, siga as instruções de configuração de Python no Guia de início rápido do Pub/Sub usando bibliotecas de cliente. Para mais informações, consulte a documentação de referência da API Pub/Sub Python.

Para se autenticar no Pub/Sub, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

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_client = SchemaServiceClient()
schema_path = schema_client.schema_path(project_id, schema_id)

for schema in schema_client.list_schema_revisions(request={"name": schema_path}):
    print(schema)

print("Listed schema revisions.")

A seguir

Para pesquisar e filtrar amostras de código para outros produtos do Google Cloud, consulte o navegador de amostra do Google Cloud.