Mencantumkan skema

Mencantumkan resource skema dalam project.

Mempelajari lebih lanjut

Untuk dokumentasi mendetail yang menyertakan contoh kode ini, lihat artikel berikut:

Contoh kode

C++

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan C++ dalam Panduan memulai Pub/Sub menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API C++ Pub/Sub.

Untuk melakukan autentikasi ke Pub/Sub, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

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

C#

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan C# dalam Panduan memulai Pub/Sub menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API C# Pub/Sub.

Untuk melakukan autentikasi ke Pub/Sub, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.


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

public class ListSchemasSample
{
    public IEnumerable<Schema> ListSchemas(string projectId)
    {
        SchemaServiceClient schemaService = SchemaServiceClient.Create();
        ProjectName projectName = ProjectName.FromProject(projectId);
        var schemas = schemaService.ListSchemas(projectName);
        return schemas;
    }
}

Go

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Go dalam Panduan memulai Pub/Sub menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Go Pub/Sub.

Untuk melakukan autentikasi ke Pub/Sub, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

import (
	"context"
	"fmt"
	"io"

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

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

	var schemas []*pubsubpb.Schema

	req := &pubsubpb.ListSchemasRequest{
		Parent: fmt.Sprintf("projects/%s", projectID),
		View:   pubsubpb.SchemaView_FULL,
	}
	schemaIter := client.ListSchemas(ctx, req)
	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: %#v\n", sc)
		schemas = append(schemas, sc)
	}

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

Java

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Java dalam Panduan memulai Pub/Sub menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Java Pub/Sub.

Untuk melakukan autentikasi ke Pub/Sub, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

import com.google.cloud.pubsub.v1.SchemaServiceClient;
import com.google.pubsub.v1.ProjectName;
import com.google.pubsub.v1.Schema;
import java.io.IOException;

public class ListSchemas {

  public static void main(String[] args) throws Exception {
    String projectId = "example-project_id";
    listSchemas(projectId);
  }

  public static void listSchemas(String projectId) throws Exception {
    try (SchemaServiceClient client = SchemaServiceClient.create()) {
      String parent = ProjectName.of(projectId).toString();
      for (Schema schema : client.listSchemas(parent).iterateAll()) {
        System.out.println("Found schema: " + schema.getName());
      }
    }
  }
}

Node.js

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Node.js dalam Panduan memulai Pub/Sub menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Node.js Pub/Sub.

Untuk melakukan autentikasi ke Pub/Sub, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

'use strict';

const {SchemaServiceClient} = require('@google-cloud/pubsub-api');
const {status} = require('@grpc/grpc-js');

const client = new SchemaServiceClient();

/**
 * Use the listSchemas method
 *
 * @param {string} projectId - The Google Cloud project ID (for example, 'example-project-id')
 */
async function listSchemas(projectId) {
  try {
    const parent = `projects/${projectId}`;
    const request = {
      parent,
    };

    const [schemas] = await client.listSchemas(request);

    console.log(`Listed schemas for project ${projectId}:`);
    for (const schema of schemas) {
      console.log(`Schema name: ${schema.name}`);
      console.log(`Schema type: ${schema.type}`);
    }
  } catch (err) {
    if (err.code === status.NOT_FOUND) {
      console.error(`Project not found: ${err.message}`);
    } else if (err.code === status.PERMISSION_DENIED) {
      console.error(`Permission denied: ${err.message}`);
    } else if (err.code === status.INVALID_ARGUMENT) {
      console.error(`Invalid argument provided: ${err.message}`);
    } else {
      console.error(`API error: ${err.message}`);
    }
  }
}

module.exports = { listSchemas };

Node.js

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Node.js dalam Panduan memulai Pub/Sub menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Node.js Pub/Sub.

Untuk melakukan autentikasi ke Pub/Sub, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.


// 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 listSchemas() {
  for await (const s of pubSubClient.listSchemas()) {
    console.log(s.name);
  }
  console.log('Listed schemas.');
}

PHP

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan PHP dalam Panduan memulai Pub/Sub menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API PHP Pub/Sub.

Untuk melakukan autentikasi ke Pub/Sub, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

use Google\Cloud\PubSub\PubSubClient;

/**
 * List schemas in the project.
 *
 * @param string $projectId
 */
function list_schemas($projectId)
{
    $pubsub = new PubSubClient([
        'projectId' => $projectId,
    ]);

    $schemas = $pubsub->schemas();
    foreach ($schemas as $schema) {
        printf('Schema name: %s' . PHP_EOL, $schema->name());
    }
}

Python

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Python dalam Panduan memulai Pub/Sub menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Python Pub/Sub.

Untuk melakukan autentikasi ke Pub/Sub, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

import google.api_core.exceptions
from google.cloud import pubsub_v1

client = pubsub_v1.SchemaServiceClient()


def list_schemas(project_id: str) -> None:
    """Use the list_schemas method

    Args:
        project_id: The Google Cloud project ID (for example, 'example-project-id').
    """
    parent = f"projects/{project_id}"

    try:
        response = client.list_schemas(request={"parent": parent})
        for schema in response:
            print(f"Schema name: {schema.name}")
    except google.api_core.exceptions.GoogleAPICallError as error:
        print(f"API call failed: {error}")

Ruby

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Ruby dalam Panduan memulai Pub/Sub menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Ruby Pub/Sub.

Untuk melakukan autentikasi ke Pub/Sub, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.


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

schemas = schema_service.list_schemas \
  parent: pubsub.project_path,
  view: Google::Cloud::PubSub::V1::SchemaView::FULL

puts "Schemas in project:"
schemas.each do |schema|
  puts schema.name
end

Rust

use google_cloud_gax::paginator::ItemPaginator;
use google_cloud_pubsub::client::SchemaService;
use google_cloud_pubsub::model::SchemaView;

pub async fn sample(client: &SchemaService, project: &str) -> anyhow::Result<()> {
    let mut schemas = client
        .list_schemas()
        .set_parent(format!("projects/{}", project))
        .set_view(SchemaView::Full)
        .by_item();

    println!("listing schemas");
    while let Some(schemas) = schemas.next().await.transpose()? {
        println!("{schemas:?}");
    }
    println!("DONE");
    Ok(())
}

Langkah berikutnya

Untuk menelusuri dan memfilter contoh kode untuk produk Google Cloud lainnya, lihat browser contohGoogle Cloud .