Tutorial Cloud Storage (generasi ke-2)


Tutorial sederhana ini menunjukkan penulisan, deployment, dan pemicuan Cloud Function Berbasis Peristiwa dengan pemicu Cloud Storage untuk merespons peristiwa Cloud Storage.

Jika Anda mencari contoh kode untuk menggunakan Cloud Storage, buka browser contoh Google Cloud.

Tujuan

Biaya

Dalam dokumen ini, Anda menggunakan komponen Google Cloud yang dapat ditagih berikut:

  • Cloud Functions
  • Cloud Build
  • Pub/Sub
  • Cloud Storage
  • Artifact Registry
  • Eventarc
  • Cloud Logging

Untuk detailnya, lihat Harga Cloud Functions.

Untuk membuat perkiraan biaya berdasarkan proyeksi penggunaan Anda, gunakan kalkulator harga. Pengguna baru Google Cloud mungkin memenuhi syarat untuk mendapatkan uji coba gratis.


Untuk mengikuti panduan langkah demi langkah tugas ini langsung di Cloud Shell Editor, klik Pandu saya:

Pandu saya


Sebelum memulai

  1. Login ke akun Google Cloud Anda. Jika Anda baru menggunakan Google Cloud, buat akun untuk mengevaluasi performa produk kami dalam skenario dunia nyata. Pelanggan baru juga mendapatkan kredit gratis senilai $300 untuk menjalankan, menguji, dan men-deploy workload.
  2. Di konsol Google Cloud, pada halaman pemilih project, pilih atau buat project Google Cloud.

    Buka pemilih project

  3. Pastikan penagihan telah diaktifkan untuk project Google Cloud Anda.

  4. Enable the Cloud Functions, Cloud Build, Artifact Registry, Eventarc, Logging, and Pub/Sub APIs.

    Enable the APIs

  5. Menginstal Google Cloud CLI.
  6. Untuk initialize gcloud CLI, jalankan perintah berikut:

    gcloud init
  7. Di konsol Google Cloud, pada halaman pemilih project, pilih atau buat project Google Cloud.

    Buka pemilih project

  8. Pastikan penagihan telah diaktifkan untuk project Google Cloud Anda.

  9. Enable the Cloud Functions, Cloud Build, Artifact Registry, Eventarc, Logging, and Pub/Sub APIs.

    Enable the APIs

  10. Menginstal Google Cloud CLI.
  11. Untuk initialize gcloud CLI, jalankan perintah berikut:

    gcloud init
  12. Jika Anda sudah menginstal gcloud CLI, update dengan menjalankan perintah berikut:

    gcloud components update
  13. Menyiapkan lingkungan pengembangan:

Prasyarat

  1. Buat bucket regional, dengan YOUR_BUCKET_NAME sebagai nama bucket yang unik secara global, dan REGION adalah region tempat Anda berencana men-deploy fungsi:

    gsutil mb -l REGION gs://YOUR_BUCKET_NAME
    
  2. Untuk menggunakan fungsi Cloud Storage, berikan peran pubsub.publisher ke akun layanan Cloud Storage:

    PROJECT_ID=$(gcloud config get-value project)
    PROJECT_NUMBER=$(gcloud projects list --filter="project_id:$PROJECT_ID" --format='value(project_number)')
    
    SERVICE_ACCOUNT=$(gsutil kms serviceaccount -p $PROJECT_NUMBER)
    
    gcloud projects add-iam-policy-binding $PROJECT_ID \
      --member serviceAccount:$SERVICE_ACCOUNT \
      --role roles/pubsub.publisher
    

Menyiapkan aplikasi

  1. Clone repositori aplikasi contoh ke komputer lokal Anda:

    Node.js

    git clone https://github.com/GoogleCloudPlatform/nodejs-docs-samples.git

    Atau, Anda dapat mendownload sampel sebagai file ZIP dan mengekstraknya.

    Python

    git clone https://github.com/GoogleCloudPlatform/python-docs-samples.git

    Atau, Anda dapat mendownload sampel sebagai file ZIP dan mengekstraknya.

    Go

    git clone https://github.com/GoogleCloudPlatform/golang-samples.git

    Atau, Anda dapat mendownload sampel sebagai file ZIP dan mengekstraknya.

    Java

    git clone https://github.com/GoogleCloudPlatform/java-docs-samples.git

    Atau, Anda dapat mendownload sampel sebagai file ZIP dan mengekstraknya.

    C#

    git clone https://github.com/GoogleCloudPlatform/dotnet-docs-samples.git

    Atau, Anda dapat mendownload sampel sebagai file ZIP dan mengekstraknya.

    Ruby

    git clone https://github.com/GoogleCloudPlatform/ruby-docs-samples.git

    Atau, Anda dapat mendownload sampel sebagai file ZIP dan mengekstraknya.

    PHP

    git clone https://github.com/GoogleCloudPlatform/php-docs-samples.git

    Atau, Anda dapat mendownload sampel sebagai file ZIP dan mengekstraknya.

  2. Ubah ke direktori yang memuat kode contoh Cloud Functions:

    Node.js

    cd nodejs-docs-samples/functions/v2/helloGCS/

    Python

    cd python-docs-samples/functions/v2/storage/

    Go

    cd golang-samples/functions/functionsv2/hellostorage/

    Java

    cd java-docs-samples/functions/v2/hello-gcs/

    C#

    cd dotnet-docs-samples/functions/helloworld/HelloGcs/

    Ruby

    cd ruby-docs-samples/functions/helloworld/storage/

    PHP

    cd php-docs-samples/functions/helloworld_storage/

Men-deploy dan memicu fungsi

Fungsi Cloud Storage didasarkan pada notifikasi Pub/Sub dari Cloud Storage dan mendukung jenis peristiwa serupa:

Bagian berikut menjelaskan cara men-deploy dan memicu fungsi untuk setiap jenis peristiwa ini.

Finalisasi Objek

Peristiwa penyelesaian objek dipicu saat "penulisan" Objek Cloud Storage berhasil diselesaikan. Secara khusus, hal ini berarti bahwa membuat objek baru atau menimpa objek yang ada akan memicu peristiwa ini. Operasi update metadata dan arsip akan diabaikan oleh pemicu ini.

Finalisasi Objek: men-deploy fungsi

Lihat fungsi sampel, yang menangani peristiwa Cloud Storage:

Node.js

const functions = require('@google-cloud/functions-framework');

// Register a CloudEvent callback with the Functions Framework that will
// be triggered by Cloud Storage.
functions.cloudEvent('helloGCS', cloudEvent => {
  console.log(`Event ID: ${cloudEvent.id}`);
  console.log(`Event Type: ${cloudEvent.type}`);

  const file = cloudEvent.data;
  console.log(`Bucket: ${file.bucket}`);
  console.log(`File: ${file.name}`);
  console.log(`Metageneration: ${file.metageneration}`);
  console.log(`Created: ${file.timeCreated}`);
  console.log(`Updated: ${file.updated}`);
});

Python

from cloudevents.http import CloudEvent

import functions_framework

# Triggered by a change in a storage bucket
@functions_framework.cloud_event
def hello_gcs(cloud_event: CloudEvent) -> tuple:
    """This function is triggered by a change in a storage bucket.

    Args:
        cloud_event: The CloudEvent that triggered this function.
    Returns:
        The event ID, event type, bucket, name, metageneration, and timeCreated.
    """
    data = cloud_event.data

    event_id = cloud_event["id"]
    event_type = cloud_event["type"]

    bucket = data["bucket"]
    name = data["name"]
    metageneration = data["metageneration"]
    timeCreated = data["timeCreated"]
    updated = data["updated"]

    print(f"Event ID: {event_id}")
    print(f"Event type: {event_type}")
    print(f"Bucket: {bucket}")
    print(f"File: {name}")
    print(f"Metageneration: {metageneration}")
    print(f"Created: {timeCreated}")
    print(f"Updated: {updated}")

    return event_id, event_type, bucket, name, metageneration, timeCreated, updated

Go


// Package helloworld provides a set of Cloud Functions samples.
package helloworld

import (
	"context"
	"fmt"
	"log"

	"github.com/GoogleCloudPlatform/functions-framework-go/functions"
	"github.com/cloudevents/sdk-go/v2/event"
	"github.com/googleapis/google-cloudevents-go/cloud/storagedata"
	"google.golang.org/protobuf/encoding/protojson"
)

func init() {
	functions.CloudEvent("HelloStorage", helloStorage)
}

// helloStorage consumes a CloudEvent message and logs details about the changed object.
func helloStorage(ctx context.Context, e event.Event) error {
	log.Printf("Event ID: %s", e.ID())
	log.Printf("Event Type: %s", e.Type())

	var data storagedata.StorageObjectData
	if err := protojson.Unmarshal(e.Data(), &data); err != nil {
		return fmt.Errorf("protojson.Unmarshal: %w", err)
	}

	log.Printf("Bucket: %s", data.GetBucket())
	log.Printf("File: %s", data.GetName())
	log.Printf("Metageneration: %d", data.GetMetageneration())
	log.Printf("Created: %s", data.GetTimeCreated().AsTime())
	log.Printf("Updated: %s", data.GetUpdated().AsTime())
	return nil
}

Java

import com.google.cloud.functions.CloudEventsFunction;
import com.google.events.cloud.storage.v1.StorageObjectData;
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.util.JsonFormat;
import io.cloudevents.CloudEvent;
import java.nio.charset.StandardCharsets;
import java.util.logging.Logger;

public class HelloGcs implements CloudEventsFunction {
  private static final Logger logger = Logger.getLogger(HelloGcs.class.getName());

  @Override
  public void accept(CloudEvent event) throws InvalidProtocolBufferException {
    logger.info("Event: " + event.getId());
    logger.info("Event Type: " + event.getType());

    if (event.getData() == null) {
      logger.warning("No data found in cloud event payload!");
      return;
    }

    String cloudEventData = new String(event.getData().toBytes(), StandardCharsets.UTF_8);
    StorageObjectData.Builder builder = StorageObjectData.newBuilder();
    JsonFormat.parser().merge(cloudEventData, builder);
    StorageObjectData data = builder.build();

    logger.info("Bucket: " + data.getBucket());
    logger.info("File: " + data.getName());
    logger.info("Metageneration: " + data.getMetageneration());
    logger.info("Created: " + data.getTimeCreated());
    logger.info("Updated: " + data.getUpdated());
  }
}

C#

using CloudNative.CloudEvents;
using Google.Cloud.Functions.Framework;
using Google.Events.Protobuf.Cloud.Storage.V1;
using Microsoft.Extensions.Logging;
using System.Threading;
using System.Threading.Tasks;

namespace HelloGcs;

 /// <summary>
 /// Example Cloud Storage-triggered function.
 /// This function can process any event from Cloud Storage.
 /// </summary>
public class Function : ICloudEventFunction<StorageObjectData>
{
    private readonly ILogger _logger;

    public Function(ILogger<Function> logger) =>
        _logger = logger;

    public Task HandleAsync(CloudEvent cloudEvent, StorageObjectData data, CancellationToken cancellationToken)
    {
        _logger.LogInformation("Event: {event}", cloudEvent.Id);
        _logger.LogInformation("Event Type: {type}", cloudEvent.Type);
        _logger.LogInformation("Bucket: {bucket}", data.Bucket);
        _logger.LogInformation("File: {file}", data.Name);
        _logger.LogInformation("Metageneration: {metageneration}", data.Metageneration);
        _logger.LogInformation("Created: {created:s}", data.TimeCreated?.ToDateTimeOffset());
        _logger.LogInformation("Updated: {updated:s}", data.Updated?.ToDateTimeOffset());
        return Task.CompletedTask;
    }
}

Ruby

require "functions_framework"

FunctionsFramework.cloud_event "hello_gcs" do |event|
  # This function supports all Cloud Storage events.
  # The `event` parameter is a CloudEvents::Event::V1 object.
  # See https://cloudevents.github.io/sdk-ruby/latest/CloudEvents/Event/V1.html
  payload = event.data

  logger.info "Event: #{event.id}"
  logger.info "Event Type: #{event.type}"
  logger.info "Bucket: #{payload['bucket']}"
  logger.info "File: #{payload['name']}"
  logger.info "Metageneration: #{payload['metageneration']}"
  logger.info "Created: #{payload['timeCreated']}"
  logger.info "Updated: #{payload['updated']}"
end

PHP


use CloudEvents\V1\CloudEventInterface;
use Google\CloudFunctions\FunctionsFramework;

// Register the function with Functions Framework.
// This enables omitting the `FUNCTIONS_SIGNATURE_TYPE=cloudevent` environment
// variable when deploying. The `FUNCTION_TARGET` environment variable should
// match the first parameter.
FunctionsFramework::cloudEvent('helloGCS', 'helloGCS');

function helloGCS(CloudEventInterface $cloudevent)
{
    // This function supports all Cloud Storage event types.
    $log = fopen(getenv('LOGGER_OUTPUT') ?: 'php://stderr', 'wb');
    $data = $cloudevent->getData();
    fwrite($log, 'Event: ' . $cloudevent->getId() . PHP_EOL);
    fwrite($log, 'Event Type: ' . $cloudevent->getType() . PHP_EOL);
    fwrite($log, 'Bucket: ' . $data['bucket'] . PHP_EOL);
    fwrite($log, 'File: ' . $data['name'] . PHP_EOL);
    fwrite($log, 'Metageneration: ' . $data['metageneration'] . PHP_EOL);
    fwrite($log, 'Created: ' . $data['timeCreated'] . PHP_EOL);
    fwrite($log, 'Updated: ' . $data['updated'] . PHP_EOL);
}

Untuk men-deploy fungsi, jalankan perintah berikut di direktori tempat kode contoh berada:

Node.js

gcloud functions deploy nodejs-finalize-function \
--gen2 \
--runtime=nodejs20 \
--region=REGION \
--source=. \
--entry-point=helloGCS \
--trigger-event-filters="type=google.cloud.storage.object.v1.finalized" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"

Gunakan flag --runtime untuk menentukan ID runtime dari versi Node.js yang didukung untuk menjalankan fungsi Anda.

Python

gcloud functions deploy python-finalize-function \
--gen2 \
--runtime=python312 \
--region=REGION \
--source=. \
--entry-point=hello_gcs \
--trigger-event-filters="type=google.cloud.storage.object.v1.finalized" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"

Gunakan flag --runtime untuk menentukan ID runtime versi Python yang didukung untuk menjalankan fungsi Anda.

Go

gcloud functions deploy go-finalize-function \
--gen2 \
--runtime=go121 \
--region=REGION \
--source=. \
--entry-point=HelloStorage \
--trigger-event-filters="type=google.cloud.storage.object.v1.finalized" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"

Gunakan flag --runtime untuk menentukan ID runtime versi Go yang didukung untuk menjalankan fungsi Anda.

Java

gcloud functions deploy java-finalize-function \
--gen2 \
--runtime=java17 \
--region=REGION \
--source=. \
--entry-point=functions.HelloGcs \
--memory=512MB \
--trigger-event-filters="type=google.cloud.storage.object.v1.finalized" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"

Gunakan flag --runtime untuk menentukan ID runtime versi Java yang didukung guna menjalankan fungsi Anda.

C#

gcloud functions deploy csharp-finalize-function \
--gen2 \
--runtime=dotnet6 \
--region=REGION \
--source=. \
--entry-point=HelloGcs.Function \
--trigger-event-filters="type=google.cloud.storage.object.v1.finalized" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"

Gunakan flag --runtime untuk menentukan ID runtime versi .NET yang didukung guna menjalankan fungsi Anda.

Ruby

gcloud functions deploy ruby-finalize-function \
--gen2 \
--runtime=ruby32 \
--region=REGION \
--source=. \
--entry-point=hello_gcs \
--trigger-event-filters="type=google.cloud.storage.object.v1.finalized" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"

Gunakan flag --runtime untuk menentukan ID runtime versi Ruby yang didukung untuk menjalankan fungsi Anda.

PHP

gcloud functions deploy php-finalize-function \
--gen2 \
--runtime=php82 \
--region=REGION \
--source=. \
--entry-point=helloGCS \
--trigger-event-filters="type=google.cloud.storage.object.v1.finalized" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"

Gunakan tanda --runtime untuk menentukan ID runtime versi PHP yang didukung untuk menjalankan fungsi Anda.

Ganti kode berikut:

  • REGION: Nama region Google Cloud tempat Anda ingin men-deploy fungsi (misalnya, us-west1).
  • YOUR_BUCKET_NAME: Nama bucket Cloud Storage yang memicu fungsi. Saat men-deploy fungsi generasi ke-2, tentukan nama bucket saja tanpa awalan gs://; misalnya, --trigger-event-filters="bucket=my-bucket".

Finalisasi Objek: memicu fungsi

Uji fungsi dengan mengupload file ke bucket Anda:

echo "Hello World" > test-finalize.txt
gsutil cp test-finalize.txt gs://YOUR_BUCKET_NAME/test-finalize.txt

Anda akan melihat CloudEvent yang diterima di log:

gcloud functions logs read YOUR_FUNCTION_NAME --region REGION --gen2 --limit=10

Penghapusan Objek

Peristiwa penghapusan objek paling berguna untuk bucket non-pembuatan versi. Peristiwa ini dipicu saat objek versi lama dihapus. Selain itu, peristiwa ini dipicu saat objek ditimpa. Pemicu penghapusan objek juga dapat digunakan dengan bucket pembuatan versi, yang memicu saat versi objek dihapus secara permanen.

Penghapusan Objek: men-deploy fungsi

Dengan menggunakan kode contoh yang sama seperti dalam contoh penyelesaian, deploy fungsi dengan penghapusan objek sebagai peristiwa pemicu. Jalankan perintah berikut di direktori tempat kode contoh berada:

Node.js

gcloud functions deploy nodejs-delete-function \
--gen2 \
--runtime=nodejs20 \
--region=REGION \
--source=. \
--entry-point=helloGCS \
--trigger-event-filters="type=google.cloud.storage.object.v1.deleted" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"

Gunakan flag --runtime untuk menentukan ID runtime dari versi Node.js yang didukung untuk menjalankan fungsi Anda.

Python

gcloud functions deploy python-delete-function \
--gen2 \
--runtime=python312 \
--region=REGION \
--source=. \
--entry-point=hello_gcs \
--trigger-event-filters="type=google.cloud.storage.object.v1.deleted" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"

Gunakan flag --runtime untuk menentukan ID runtime versi Python yang didukung untuk menjalankan fungsi Anda.

Go

gcloud functions deploy go-delete-function \
--gen2 \
--runtime=go121 \
--region=REGION \
--source=. \
--entry-point=HelloStorage \
--trigger-event-filters="type=google.cloud.storage.object.v1.deleted" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"

Gunakan flag --runtime untuk menentukan ID runtime versi Go yang didukung untuk menjalankan fungsi Anda.

Java

gcloud functions deploy java-delete-function \
--gen2 \
--runtime=java17 \
--region=REGION \
--source=. \
--entry-point=functions.HelloGcs \
--memory=512MB \
--trigger-event-filters="type=google.cloud.storage.object.v1.deleted" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"

Gunakan flag --runtime untuk menentukan ID runtime versi Java yang didukung guna menjalankan fungsi Anda.

C#

gcloud functions deploy csharp-delete-function \
--gen2 \
--runtime=dotnet6 \
--region=REGION \
--source=. \
--entry-point=HelloGcs.Function \
--trigger-event-filters="type=google.cloud.storage.object.v1.deleted" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"

Gunakan flag --runtime untuk menentukan ID runtime versi .NET yang didukung guna menjalankan fungsi Anda.

Ruby

gcloud functions deploy ruby-delete-function \
--gen2 \
--runtime=ruby32 \
--region=REGION \
--source=. \
--entry-point=hello_gcs \
--trigger-event-filters="type=google.cloud.storage.object.v1.deleted" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"

Gunakan flag --runtime untuk menentukan ID runtime versi Ruby yang didukung untuk menjalankan fungsi Anda.

PHP

gcloud functions deploy php-delete-function \
--gen2 \
--runtime=php82 \
--region=REGION \
--source=. \
--entry-point=helloGCS \
--trigger-event-filters="type=google.cloud.storage.object.v1.deleted" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"

Gunakan tanda --runtime untuk menentukan ID runtime versi PHP yang didukung untuk menjalankan fungsi Anda.

Ganti kode berikut:

  • REGION: Nama region Google Cloud tempat Anda ingin men-deploy fungsi (misalnya, us-west1).
  • YOUR_BUCKET_NAME: Nama bucket Cloud Storage yang memicu fungsi. Saat men-deploy fungsi generasi ke-2, tentukan nama bucket saja tanpa awalan gs://; misalnya, --trigger-event-filters="bucket=my-bucket".

Penghapusan Objek: memicu fungsi

Untuk memicu fungsi:

  1. Buat file test-delete.txt kosong di direktori tempat kode contoh berada.

  2. Pastikan bucket Anda tidak membuat versi:

    gsutil versioning set off gs://YOUR_BUCKET_NAME
    
  3. Upload file ke Cloud Storage:

    gsutil cp test-delete.txt gs://YOUR_BUCKET_NAME
    

    dengan YOUR_BUCKET_NAME adalah nama bucket Cloud Storage tempat Anda akan mengupload file pengujian. Pada tahap ini, fungsi seharusnya belum dijalankan.

  4. Hapus file untuk memicu fungsi:

    gsutil rm gs://YOUR_BUCKET_NAME/test-delete.txt
    
  5. Anda akan melihat CloudEvent yang diterima di log:

    gcloud functions logs read YOUR_FUNCTION_NAME --region REGION --gen2 --limit=10

Perhatikan bahwa mungkin perlu waktu beberapa saat hingga fungsi selesai dijalankan.

Pengarsipan Objek

Peristiwa arsip objek hanya dapat digunakan dengan bucket pembuatan versi. Peristiwa dipicu saat versi objek sebelumnya diarsipkan. Secara khusus, hal ini berarti bahwa saat objek ditimpa atau dihapus, peristiwa arsip akan dipicu.

Arsip Objek: men-deploy fungsi

Dengan menggunakan kode contoh yang sama seperti dalam contoh penyelesaian, deploy fungsi dengan arsip objek sebagai peristiwa pemicu. Jalankan perintah berikut di direktori tempat kode contoh berada:

Node.js

gcloud functions deploy nodejs-archive-function \
--gen2 \
--runtime=nodejs20 \
--region=REGION \
--source=. \
--entry-point=helloGCS \
--trigger-event-filters="type=google.cloud.storage.object.v1.archived" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"

Gunakan flag --runtime untuk menentukan ID runtime dari versi Node.js yang didukung untuk menjalankan fungsi Anda.

Python

gcloud functions deploy python-archive-function \
--gen2 \
--runtime=python312 \
--region=REGION \
--source=. \
--entry-point=hello_gcs \
--trigger-event-filters="type=google.cloud.storage.object.v1.archived" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"

Gunakan flag --runtime untuk menentukan ID runtime versi Python yang didukung untuk menjalankan fungsi Anda.

Go

gcloud functions deploy go-archive-function \
--gen2 \
--runtime=go121 \
--region=REGION \
--source=. \
--entry-point=HelloStorage \
--trigger-event-filters="type=google.cloud.storage.object.v1.archived" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"

Gunakan flag --runtime untuk menentukan ID runtime versi Go yang didukung untuk menjalankan fungsi Anda.

Java

gcloud functions deploy java-archive-function \
--gen2 \
--runtime=java17 \
--region=REGION \
--source=. \
--entry-point=functions.HelloGcs \
--memory=512MB \
--trigger-event-filters="type=google.cloud.storage.object.v1.archived" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"

Gunakan flag --runtime untuk menentukan ID runtime versi Java yang didukung guna menjalankan fungsi Anda.

C#

gcloud functions deploy csharp-archive-function \
--gen2 \
--runtime=dotnet6 \
--region=REGION \
--source=. \
--entry-point=HelloGcs.Function \
--trigger-event-filters="type=google.cloud.storage.object.v1.archived" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"

Gunakan flag --runtime untuk menentukan ID runtime versi .NET yang didukung guna menjalankan fungsi Anda.

Ruby

gcloud functions deploy ruby-archive-function \
--gen2 \
--runtime=ruby32 \
--region=REGION \
--source=. \
--entry-point=hello_gcs \
--trigger-event-filters="type=google.cloud.storage.object.v1.archived" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"

Gunakan flag --runtime untuk menentukan ID runtime versi Ruby yang didukung untuk menjalankan fungsi Anda.

PHP

gcloud functions deploy php-archive-function \
--gen2 \
--runtime=php82 \
--region=REGION \
--source=. \
--entry-point=helloGCS \
--trigger-event-filters="type=google.cloud.storage.object.v1.archived" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"

Gunakan tanda --runtime untuk menentukan ID runtime versi PHP yang didukung untuk menjalankan fungsi Anda.

Ganti kode berikut:

  • REGION: Nama region Google Cloud tempat Anda ingin men-deploy fungsi (misalnya, us-west1).
  • YOUR_BUCKET_NAME: Nama bucket Cloud Storage yang memicu fungsi. Saat men-deploy fungsi generasi ke-2, tentukan nama bucket saja tanpa awalan gs://; misalnya, --trigger-event-filters="bucket=my-bucket".

Arsip Objek: memicu fungsi

Untuk memicu fungsi:

  1. Buat file test-archive.txt kosong di direktori tempat kode contoh berada.

  2. Pastikan bucket Anda mengaktifkan pembuatan versi:

    gsutil versioning set on gs://YOUR_BUCKET_NAME
    
  3. Upload file ke Cloud Storage:

    gsutil cp test-archive.txt gs://YOUR_BUCKET_NAME
    

    dengan YOUR_BUCKET_NAME adalah nama bucket Cloud Storage tempat Anda akan mengupload file pengujian. Pada tahap ini, fungsi seharusnya belum dijalankan.

  4. Arsipkan file untuk memicu fungsi:

    gsutil rm gs://YOUR_BUCKET_NAME/test-archive.txt
    
  5. Anda akan melihat CloudEvent yang diterima di log:

    gcloud functions logs read YOUR_FUNCTION_NAME --region REGION --gen2 --limit=10

Update Metadata Objek

Peristiwa pembaruan metadata dipicu saat metadata objek yang ada diperbarui.

Update Metadata Objek: men-deploy fungsi

Dengan menggunakan kode contoh yang sama seperti pada contoh penyelesaian, deploy fungsi dengan pembaruan metadata sebagai peristiwa pemicu. Jalankan perintah berikut di direktori tempat kode contoh berada:

Node.js

gcloud functions deploy nodejs-metadata-function \
--gen2 \
--runtime=nodejs20 \
--region=REGION \
--source=. \
--entry-point=helloGCS \
--trigger-event-filters="type=google.cloud.storage.object.v1.metadataUpdated" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"

Gunakan flag --runtime untuk menentukan ID runtime dari versi Node.js yang didukung untuk menjalankan fungsi Anda.

Python

gcloud functions deploy python-metadata-function \
--gen2 \
--runtime=python312 \
--region=REGION \
--source=. \
--entry-point=hello_gcs \
--trigger-event-filters="type=google.cloud.storage.object.v1.metadataUpdated" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"

Gunakan flag --runtime untuk menentukan ID runtime versi Python yang didukung untuk menjalankan fungsi Anda.

Go

gcloud functions deploy go-metadata-function \
--gen2 \
--runtime=go121 \
--region=REGION \
--source=. \
--entry-point=HelloStorage \
--trigger-event-filters="type=google.cloud.storage.object.v1.metadataUpdated" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"

Gunakan flag --runtime untuk menentukan ID runtime versi Go yang didukung untuk menjalankan fungsi Anda.

Java

gcloud functions deploy java-metadata-function \
--gen2 \
--runtime=java17 \
--region=REGION \
--source=. \
--entry-point=functions.HelloGcs \
--memory=512MB \
--trigger-event-filters="type=google.cloud.storage.object.v1.metadataUpdated" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"

Gunakan flag --runtime untuk menentukan ID runtime versi Java yang didukung guna menjalankan fungsi Anda.

C#

gcloud functions deploy csharp-metadata-function \
--gen2 \
--runtime=dotnet6 \
--region=REGION \
--source=. \
--entry-point=HelloGcs.Function \
--trigger-event-filters="type=google.cloud.storage.object.v1.metadataUpdated" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"

Gunakan flag --runtime untuk menentukan ID runtime versi .NET yang didukung guna menjalankan fungsi Anda.

Ruby

gcloud functions deploy ruby-metadata-function \
--gen2 \
--runtime=ruby32 \
--region=REGION \
--source=. \
--entry-point=hello_gcs \
--trigger-event-filters="type=google.cloud.storage.object.v1.metadataUpdated" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"

Gunakan flag --runtime untuk menentukan ID runtime versi Ruby yang didukung untuk menjalankan fungsi Anda.

PHP

gcloud functions deploy php-metadata-function \
--gen2 \
--runtime=php82 \
--region=REGION \
--source=. \
--entry-point=helloGCS \
--trigger-event-filters="type=google.cloud.storage.object.v1.metadataUpdated" \
--trigger-event-filters="bucket=YOUR_BUCKET_NAME"

Gunakan tanda --runtime untuk menentukan ID runtime versi PHP yang didukung untuk menjalankan fungsi Anda.

Ganti kode berikut:

  • REGION: Nama region Google Cloud tempat Anda ingin men-deploy fungsi (misalnya, us-west1).
  • YOUR_BUCKET_NAME: Nama bucket Cloud Storage yang memicu fungsi. Saat men-deploy fungsi generasi ke-2, tentukan nama bucket saja tanpa awalan gs://; misalnya, --trigger-event-filters="bucket=my-bucket".

Pembaruan Metadata Objek: memicu fungsi

Untuk memicu fungsi:

  1. Buat file test-metadata.txt kosong di direktori tempat kode contoh berada.

  2. Pastikan bucket Anda tidak membuat versi:

    gsutil versioning set off gs://YOUR_BUCKET_NAME
    
  3. Upload file ke Cloud Storage:

    gsutil cp test-metadata.txt gs://YOUR_BUCKET_NAME
    

    dengan YOUR_BUCKET_NAME adalah nama bucket Cloud Storage tempat Anda akan mengupload file pengujian. Pada tahap ini, fungsi seharusnya belum dijalankan.

  4. Perbarui metadata file:

    gsutil -m setmeta -h "Content-Type:text/plain" gs://YOUR_BUCKET_NAME/test-metadata.txt
    
  5. Anda akan melihat CloudEvent yang diterima di log:

    gcloud functions logs read YOUR_FUNCTION_NAME --region REGION --gen2 --limit=10

Pembersihan

Agar tidak perlu membayar biaya pada akun Google Cloud Anda untuk resource yang digunakan dalam tutorial ini, hapus project yang berisi resource tersebut, atau simpan project dan hapus setiap resource.

Menghapus project

Cara termudah untuk menghilangkan penagihan adalah dengan menghapus project yang Anda buat untuk tutorial.

Untuk menghapus project:

  1. Di konsol Google Cloud, buka halaman Manage resource.

    Buka Manage resource

  2. Pada daftar project, pilih project yang ingin Anda hapus, lalu klik Delete.
  3. Pada dialog, ketik project ID, lalu klik Shut down untuk menghapus project.

Menghapus Cloud Functions

Menghapus Cloud Functions tidak akan menghapus resource apa pun yang tersimpan di Cloud Storage.

Untuk menghapus Cloud Functions yang Anda buat dalam tutorial ini, jalankan perintah berikut:

gcloud functions delete YOUR_FUNCTION_NAME --gen2 --region REGION

Anda juga dapat menghapus Cloud Functions dari Konsol Google Cloud.

Langkah selanjutnya