Recupera una revisione dello schema

Recupera una revisione dello schema

Per saperne di più

Per la documentazione dettagliata che include questo esempio di codice, vedi quanto segue:

Esempio di codice

C++

Prima di provare questo esempio, segui le istruzioni di configurazione di C++ nella guida rapida di Pub/Sub sull'utilizzo delle librerie client. Per maggiori informazioni, consulta la documentazione di riferimento dell'API C++ di Pub/Sub.

Per eseguire l'autenticazione in Pub/Sub, configura le Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

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#

Prima di provare questo esempio, segui le istruzioni di configurazione di C# nella guida rapida di Pub/Sub sull'utilizzo delle librerie client. Per maggiori informazioni, consulta la documentazione di riferimento dell'API C# di Pub/Sub.

Per eseguire l'autenticazione in Pub/Sub, configura le Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.


using Google.Cloud.PubSub.V1;

public class GetSchemaRevisionSample
{
    public Schema GetSchemaRevision(string projectId, string schemaId, string revisionId)
    {
        SchemaServiceClient schemaService = SchemaServiceClient.Create();
        GetSchemaRequest request = new GetSchemaRequest
        {
            SchemaName = SchemaName.FromProjectSchema(projectId, schemaId + "@" + revisionId),
            View = SchemaView.Full
        };

        return schemaService.GetSchema(request);
    }
}

Go

Prima di provare questo esempio, segui le istruzioni di configurazione di Go nella guida rapida di Pub/Sub sull'utilizzo delle librerie client. Per maggiori informazioni, consulta la documentazione di riferimento dell'API Go di Pub/Sub.

Per eseguire l'autenticazione in Pub/Sub, configura le Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

import (
	"context"
	"fmt"
	"io"

	"cloud.google.com/go/pubsub"
)

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

	s, err := client.Schema(ctx, schemaID, pubsub.SchemaViewFull)
	if err != nil {
		return fmt.Errorf("client.Schema revision: %w", err)
	}
	fmt.Fprintf(w, "Got schema revision: %#v\n", s)
	return nil
}

Java

Prima di provare questo esempio, segui le istruzioni di configurazione di Java nella guida rapida di Pub/Sub sull'utilizzo delle librerie client. Per maggiori informazioni, consulta la documentazione di riferimento dell'API Java di Pub/Sub.

Per eseguire l'autenticazione in Pub/Sub, configura le Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.


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

/**
 * TODO(developer): Uncomment this variable before running the sample.
 */
// const schemaNameOrId = 'YOUR_SCHEMA_NAME_OR_ID';
// const revisionId = 'YOUR_REVISION_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 getSchemaRevision(schemaNameOrId, revisionId) {
  const schema = pubSubClient.schema(schemaNameOrId);
  const name = await schema.getName();

  // Use the gapic client to delete the schema revision.
  const schemaClient = await pubSubClient.getSchemaClient();
  const schemaInfo = await schemaClient.getSchema({
    name: `${name}@${revisionId}`,
  });

  console.log(
    `Schema ${name}@${revisionId} info: ${JSON.stringify(schemaInfo, null, 4)}.`
  );
}

Node.js

/**
 * TODO(developer): Uncomment this variable before running the sample.
 */
// const schemaNameOrId = 'YOUR_SCHEMA_NAME_OR_ID';
// const revisionId = 'YOUR_REVISION_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 getSchemaRevision(schemaNameOrId: string, revisionId: string) {
  const schema = pubSubClient.schema(schemaNameOrId);
  const name = await schema.getName();

  // Use the gapic client to delete the schema revision.
  const schemaClient = await pubSubClient.getSchemaClient();
  const schemaInfo = await schemaClient.getSchema({
    name: `${name}@${revisionId}`,
  });

  console.log(
    `Schema ${name}@${revisionId} info: ${JSON.stringify(schemaInfo, null, 4)}.`
  );
}

PHP

Prima di provare questo esempio, segui le istruzioni di configurazione di PHP nella guida rapida di Pub/Sub sull'utilizzo delle librerie client. Per maggiori informazioni, consulta la documentazione di riferimento dell'API PHP di Pub/Sub.

Per eseguire l'autenticazione in Pub/Sub, configura le Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.


/**
 * Gets a schema revision.
 *
 * @param string $projectId The ID of your Google Cloud Platform project.
 * @param string $schemaId The ID of the schema.
 * @param string $schemaRevisionId name of the schema.
 */
function get_schema_revision(string $projectId, string $schemaId, string $schemaRevisionId)
{
    $client = new PubSubClient([
        'projectId' => $projectId
    ]);

    $schemaPath = $schemaId . '@' . $schemaRevisionId;

    try {
        $schema = $client->schema($schemaPath);
        $info = $schema->info();
        printf('Got the schema revision: %s@%s' . PHP_EOL, $info['name'], $info['revisionId']);
    } catch (NotFoundException $ex) {
        printf('%s not found' . PHP_EOL, $schemaId);
    }
}

Python

Prima di provare questo esempio, segui le istruzioni di configurazione di Python nella guida rapida di Pub/Sub sull'utilizzo delle librerie client. Per maggiori informazioni, consulta la documentazione di riferimento dell'API Python di Pub/Sub.

Per eseguire l'autenticazione in Pub/Sub, configura le Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

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

Passaggi successivi

Per cercare e filtrare esempi di codice per altri prodotti Google Cloud, consulta il browser di esempio Google Cloud.