Mendapatkan notifikasi Pub/Sub

Memberikan contoh cara mendapatkan metadata notifikasi Pub/Sub.

Jelajahi lebih lanjut

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

Contoh kode

C++

Untuk informasi selengkapnya, lihat Dokumentasi referensi Cloud Storage C++ API.

Untuk melakukan autentikasi ke Cloud Storage, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
   std::string const& notification_id) {
  StatusOr<gcs::NotificationMetadata> notification =
      client.GetNotification(bucket_name, notification_id);
  if (!notification) throw std::move(notification).status();

  std::cout << "Notification " << notification->id() << " for bucket "
            << bucket_name << "\n";
  if (notification->object_name_prefix().empty()) {
    std::cout << "This notification is sent for all objects in the bucket\n";
  } else {
    std::cout << "This notification is sent only for objects starting with"
              << " the prefix " << notification->object_name_prefix() << "\n";
  }
  std::cout << "Full details for the notification:\n"
            << *notification << "\n";
}

C#

Untuk mengetahui informasi selengkapnya, lihatDokumentasi referensi Cloud Storage C# API.

Untuk melakukan autentikasi ke Cloud Storage, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.


using Google.Apis.Storage.v1.Data;
using Google.Cloud.Storage.V1;
using System;

public class GetPubSubNotificationSample
{
    public Notification GetPubSubNotification(
        string bucketName = "your-unique-bucket-name",
        string notificationId = "notificationId")
    {
        StorageClient storage = StorageClient.Create();
        Notification notification = storage.GetNotification(bucketName, notificationId);

        Console.WriteLine("ID: " + notification.Id);
        Console.WriteLine("Topic: " + notification.Topic);
        Console.WriteLine("EventTypes: " + notification.EventTypes);
        Console.WriteLine("CustomAttributes: " + notification.CustomAttributes);
        Console.WriteLine("PayloadFormat: " + notification.PayloadFormat);
        Console.WriteLine("ObjectNamePrefix: " + notification.ObjectNamePrefix);
        Console.WriteLine("ETag: " + notification.ETag);
        Console.WriteLine("SelfLink: " + notification.SelfLink);
        Console.WriteLine("Kind: " + notification.Kind);

        return notification;
    }
}

Go

Untuk mengetahui informasi selengkapnya, lihatDokumentasi referensi Cloud Storage Go API.

Untuk melakukan autentikasi ke Cloud Storage, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

import (
	"context"
	"fmt"
	"io"

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

// printPubsubBucketNotification gets a notification configuration for a bucket.
func printPubsubBucketNotification(w io.Writer, bucketName, notificationID string) error {
	// bucketName := "bucket-name"
	// notificationID := "notification-id"

	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %w", err)
	}
	defer client.Close()

	notifications, err := client.Bucket(bucketName).Notifications(ctx)
	if err != nil {
		return fmt.Errorf("Bucket.Notifications: %w", err)
	}

	n := notifications[notificationID]
	fmt.Fprintf(w, "Notification: %+v", n)

	return nil
}

Java

Untuk mengetahui informasi selengkapnya, lihatDokumentasi referensi Cloud Storage Java API.

Untuk melakukan autentikasi ke Cloud Storage, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

import com.google.cloud.storage.Notification;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;

public class PrintPubSubNotification {

  public static void printPubSubNotification(String bucketName, String notificationId) {
    // The ID to give your GCS bucket
    // String bucketName = "your-unique-bucket-name";

    // The Pub/Sub topic you would like to find
    // String notificationId = "your-unique-notification-id"

    Storage storage = StorageOptions.newBuilder().build().getService();
    Notification notification = storage.getNotification(bucketName, notificationId);
    System.out.println(
        "Found notification " + notification.getTopic() + " for bucket " + bucketName);
  }
}

Node.js

Untuk mengetahui informasi selengkapnya, lihatDokumentasi referensi Cloud Storage Node.js API.

Untuk melakukan autentikasi ke Cloud Storage, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// The ID of your GCS bucket
// const bucketName = 'your-unique-bucket-name';

// The ID of the notification
// const notificationId = '1';

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

async function getMetadata() {
  // Get the notification metadata
  const [metadata] = await storage
    .bucket(bucketName)
    .notification(notificationId)
    .getMetadata();

  console.log(`ID: ${metadata.id}`);
  console.log(`Topic: ${metadata.topic}`);
  console.log(`Event Types: ${metadata.event_types}`);
  console.log(`Custom Attributes: ${metadata.custom_attributes}`);
  console.log(`Payload Format: ${metadata.payload_format}`);
  console.log(`Object Name Prefix: ${metadata.object_name_prefix}`);
  console.log(`Etag: ${metadata.etag}`);
  console.log(`Self Link: ${metadata.selfLink}`);
  console.log(`Kind: ${metadata.kind}`);
}

getMetadata().catch(console.error);

PHP

Untuk mengetahui informasi selengkapnya, lihatDokumentasi referensi Cloud Storage PHP API.

Untuk melakukan autentikasi ke Cloud Storage, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.


use Google\Cloud\Storage\StorageClient;

/**
 * Lists notification configurations for a bucket.
 * This sample is used on this page:
 *   https://cloud.google.com/storage/docs/reporting-changes
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'your-bucket')
 * @param string $notificationId The ID of the notification.
 *        (e.g. 'your-notification-id')
 */
function print_pubsub_bucket_notification(
    string $bucketName,
    string $notificationId
): void {
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $notification = $bucket->notification($notificationId);
    $notificationInfo = $notification->info();

    printf(
        <<<EOF
Notification ID: %s
Topic Name: %s
Event Types: %s
Custom Attributes: %s
Payload Format: %s
Blob Name Prefix: %s
Etag: %s
Self Link: %s
EOF . PHP_EOL,
        $notification->id(),
        $notificationInfo['topic'],
        $notificationInfo['event_types'] ?? '',
        $notificationInfo['custom_attributes'] ?? '',
        $notificationInfo['payload_format'],
        $notificationInfo['blob_name_prefix'] ?? '',
        $notificationInfo['etag'],
        $notificationInfo['selfLink']
    );
}

Python

Untuk mengetahui informasi selengkapnya, lihatDokumentasi referensi Cloud Storage Python API.

Untuk melakukan autentikasi ke Cloud Storage, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

from google.cloud import storage

def print_pubsub_bucket_notification(bucket_name, notification_id):
    """Gets a notification configuration for a bucket."""
    # The ID of your GCS bucket
    # bucket_name = "your-bucket-name"
    # The ID of the notification
    # notification_id = "your-notification-id"

    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)
    notification = bucket.get_notification(notification_id)

    print(f"Notification ID: {notification.notification_id}")
    print(f"Topic Name: {notification.topic_name}")
    print(f"Event Types: {notification.event_types}")
    print(f"Custom Attributes: {notification.custom_attributes}")
    print(f"Payload Format: {notification.payload_format}")
    print(f"Blob Name Prefix: {notification.blob_name_prefix}")
    print(f"Etag: {notification.etag}")
    print(f"Self Link: {notification.self_link}")

Ruby

Untuk mengetahui informasi selengkapnya, lihatDokumentasi referensi Cloud Storage Ruby API.

Untuk melakukan autentikasi ke Cloud Storage, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, baca Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

require "google/cloud/storage"

def print_pubsub_bucket_notification bucket_name:, notification_id:
  # The ID of your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  # The ID of your notification configured for the bucket
  # notification_id = "your-notification-id"

  storage = Google::Cloud::Storage.new
  bucket  = storage.bucket bucket_name
  notification = bucket.notification notification_id

  puts "Notification ID: #{notification.id}"
  puts "Topic Name: #{notification.topic}"
  puts "Event Types: #{notification.event_types}"
  puts "Kind of Notification: #{notification.kind}"
  puts "Custom Attributes: #{notification.custom_attrs}"
  puts "Payload Format: #{notification.payload}"
  puts "Blob Name Prefix: #{notification.prefix}"
  puts "Self Link: #{notification.api_url}"
end

Langkah selanjutnya

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