Crea una nuova notifica Pub/Sub

Aggiungi una notifica Pub/Sub a un bucket Cloud Storage.

Per saperne di più

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

Esempio di codice

C++

Per saperne di più, consulta la documentazione di riferimento dell'API Cloud Storage C++.

Per eseguire l'autenticazione in Cloud Storage, configura le Credenziali predefinite dell'applicazione. Per saperne di più, vedi Configurare l'autenticazione per le librerie client.

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

  std::cout << "Successfully created notification " << notification->id()
            << " for bucket " << bucket_name << "\n";
  std::cout << "Full details for the notification:\n"
            << *notification << "\n";
}

C#

Per saperne di più, consulta la documentazione di riferimento dell'API Cloud Storage C#.

Per eseguire l'autenticazione in Cloud Storage, configura le Credenziali predefinite dell'applicazione. Per saperne di più, vedi Configurare l'autenticazione per le librerie client.


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

public class CreatePubSubNotificationSample
{
    public Notification CreatePubSubNotification(
        string bucketName = "your-unique-bucket-name",
        string topic = "my-topic")
    {
        StorageClient storage = StorageClient.Create();
        Notification notification = new Notification
        {
            Topic = topic,
            PayloadFormat = "JSON_API_V1"
        };

        Notification createdNotification = storage.CreateNotification(bucketName, notification);
        Console.WriteLine("Notification subscription created with ID: " + createdNotification.Id + " for bucket name " + bucketName);
        return createdNotification;
    }
}

Go

Per saperne di più, consulta la documentazione di riferimento dell'API Cloud Storage Go.

Per eseguire l'autenticazione in Cloud Storage, configura le Credenziali predefinite dell'applicazione. Per saperne di più, vedi Configurare l'autenticazione per le librerie client.

import (
	"context"
	"fmt"
	"io"

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

// createBucketNotification creates a notification configuration for a bucket.
func createBucketNotification(w io.Writer, projectID, bucketName, topic string) error {
	// projectID := "my-project-id"
	// bucketName := "bucket-name"
	// topic := "topic-name"

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

	notification := storage.Notification{
		TopicID:        topic,
		TopicProjectID: projectID,
		PayloadFormat:  storage.JSONPayload,
	}

	createdNotification, err := client.Bucket(bucketName).AddNotification(ctx, &notification)
	if err != nil {
		return fmt.Errorf("Bucket.AddNotification: %w", err)
	}
	fmt.Fprintf(w, "Successfully created notification with ID %s for bucket %s.\n", createdNotification.ID, bucketName)
	return nil
}

Java

Per saperne di più, consulta la documentazione di riferimento dell'API Cloud Storage Java.

Per eseguire l'autenticazione in Cloud Storage, configura le Credenziali predefinite dell'applicazione. Per saperne di più, vedi Configurare l'autenticazione per le librerie client.

import com.google.cloud.storage.Notification;
import com.google.cloud.storage.NotificationInfo;
import com.google.cloud.storage.NotificationInfo.EventType;
import com.google.cloud.storage.NotificationInfo.PayloadFormat;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import java.util.Map;

public class CreateBucketPubSubNotification {

  public static void createBucketPubSubNotification(
      String bucketName,
      String topicName,
      Map<String, String> customAttributes,
      EventType[] eventTypes,
      String objectNamePrefix,
      PayloadFormat payloadFormat) {
    // The ID to give your GCS bucket
    // String bucketName = "your-unique-bucket-name";

    // The name of the topic you would like to create a notification for
    // String topicName = "projects/{your-project}/topics/{your-topic}";

    // Any custom attributes
    // Map<String, String> customAttributes = Map.of("label", "value");

    // The object name prefix for which this notification configuration applies
    // String objectNamePrefix = "blob-";

    // Desired content of the Payload
    // PayloadFormat payloadFormat = PayloadFormat.JSON_API_V1.JSON_API_V1;

    Storage storage = StorageOptions.newBuilder().build().getService();
    NotificationInfo notificationInfo =
        NotificationInfo.newBuilder(topicName)
            .setCustomAttributes(customAttributes)
            .setEventTypes(eventTypes)
            .setObjectNamePrefix(objectNamePrefix)
            .setPayloadFormat(payloadFormat)
            .build();
    Notification notification = storage.createNotification(bucketName, notificationInfo);
    String topic = notification.getTopic();
    System.out.println("Successfully created notification for topic " + topic);
  }
}

Node.js

Per saperne di più, consulta la documentazione di riferimento dell'API Cloud Storage Node.js.

Per eseguire l'autenticazione in Cloud Storage, configura le Credenziali predefinite dell'applicazione. Per saperne di più, vedi Configurare l'autenticazione per le librerie client.

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

// The name of a topic
// const topic = 'my-topic';

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

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

async function createNotification() {
  // Creates a notification
  await storage.bucket(bucketName).createNotification(topic);

  console.log('Notification subscription created.');
}

createNotification().catch(console.error);

PHP

Per saperne di più, consulta la documentazione di riferimento dell'API Cloud Storage PHP.

Per eseguire l'autenticazione in Cloud Storage, configura le Credenziali predefinite dell'applicazione. Per saperne di più, vedi Configurare l'autenticazione per le librerie client.

use Google\Cloud\Storage\StorageClient;

/**
 * Creates a notification configuration 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. 'my-bucket')
 * @param string $topicName The name of the topic you would like to create a notification.
 *        (e.g. 'my-topic')
 */
function create_bucket_notifications(
    string $bucketName,
    string $topicName
): void {
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $notification = $bucket->createNotification($topicName);

    printf(
        'Successfully created notification with ID %s for bucket %s in topic %s' . PHP_EOL,
        $notification->id(),
        $bucketName,
        $topicName
    );
}

Python

Per saperne di più, consulta la documentazione di riferimento dell'API Cloud Storage Python.

Per eseguire l'autenticazione in Cloud Storage, configura le Credenziali predefinite dell'applicazione. Per saperne di più, vedi Configurare l'autenticazione per le librerie client.

from google.cloud import storage


def create_bucket_notifications(bucket_name, topic_name):
    """Creates a notification configuration for a bucket."""
    # The ID of your GCS bucket
    # bucket_name = "your-bucket-name"
    # The name of a topic
    # topic_name = "your-topic-name"

    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)
    notification = bucket.notification(topic_name=topic_name)
    notification.create()

    print(f"Successfully created notification with ID {notification.notification_id} for bucket {bucket_name}")

Ruby

Per saperne di più, consulta la documentazione di riferimento dell'API Cloud Storage Ruby.

Per eseguire l'autenticazione in Cloud Storage, configura le Credenziali predefinite dell'applicazione. Per saperne di più, vedi Configurare l'autenticazione per le librerie client.

require "google/cloud/storage"

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

  # The ID of the pubsub topic
  # topic_name = "your-unique-topic-name"

  storage = Google::Cloud::Storage.new
  bucket  = storage.bucket bucket_name
  notification = bucket.create_notification topic_name

  puts "Successfully created notification with ID #{notification.id} for bucket #{bucket_name}"
end

Passaggi successivi

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