Obtenir une notification Pub/Sub

Cette page fournit un exemple décrivant comment obtenir des métadonnées de notification Pub/Sub.

En savoir plus

Pour obtenir une documentation détaillée incluant cet exemple de code, consultez la page suivante :

Exemple de code

C++

Pour en savoir plus, consultez la documentation de référence de l'API Cloud Storage en langage C++.

Pour vous authentifier auprès de Cloud Storage, configurez le service Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

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#

Pour en savoir plus, consultez la documentation de référence de l'API Cloud Storage en langage C#.

Pour vous authentifier auprès de Cloud Storage, configurez le service Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.


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

Pour en savoir plus, consultez la documentation de référence de l'API Cloud Storage en langage Go.

Pour vous authentifier auprès de Cloud Storage, configurez le service Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

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

Pour en savoir plus, consultez la documentation de référence de l'API Cloud Storage en langage Java.

Pour vous authentifier auprès de Cloud Storage, configurez le service Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

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

Pour en savoir plus, consultez la documentation de référence de l'API Cloud Storage en langage Node.js.

Pour vous authentifier auprès de Cloud Storage, configurez le service Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

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

Pour en savoir plus, consultez la documentation de référence de l'API Cloud Storage en langage PHP.

Pour vous authentifier auprès de Cloud Storage, configurez le service Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.


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

Pour en savoir plus, consultez la documentation de référence de l'API Cloud Storage en langage Python.

Pour vous authentifier auprès de Cloud Storage, configurez le service Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

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

Pour en savoir plus, consultez la documentation de référence de l'API Cloud Storage en langage Ruby.

Pour vous authentifier auprès de Cloud Storage, configurez le service Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

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

Étapes suivantes

Pour rechercher et filtrer des exemples de code pour d'autres produits Google Cloud, consultez l'explorateur d'exemples Google Cloud.