Tutorial Cloud Pub/Sub (generasi ke-1)

Tutorial sederhana ini menunjukkan penulisan, deployment, dan pemicuan fungsi Cloud Run Berbasis Peristiwa dengan pemicu Pub/Sub.

Jika Anda baru menggunakan Pub/Sub dan ingin mempelajari lebih lanjut, lihat dokumentasi Pub/Sub, terutama mengelola topik dan langganan. Lihat Pemicu Pub/Sub untuk mengetahui ringkasan cara menangani topik dan langganan Pub/Sub di fungsi Cloud Run.

Jika Anda mencari contoh kode untuk menggunakan Pub/Sub sendiri, buka browser contoh.

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 contoh dalam file ZIP dan mengekstraknya.

    Python

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

    Atau, Anda dapat mendownload contoh dalam file ZIP dan mengekstraknya.

    Go

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

    Atau, Anda dapat mendownload contoh dalam file ZIP dan mengekstraknya.

    Java

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

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

    Ruby

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

    Atau, Anda dapat mendownload contoh dalam file ZIP dan mengekstraknya.

  2. Ubah ke direktori yang berisi kode contoh fungsi Cloud Run untuk mengakses Pub/Sub:

    Node.js

    cd nodejs-docs-samples/functions/helloworld/

    Python

    cd python-docs-samples/functions/helloworld/

    Go

    cd golang-samples/functions/helloworld/

    Java

    cd java-docs-samples/functions/helloworld/hello-pubsub/

    Ruby

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

  3. Lihat kode contoh:

    Node.js

    /**
     * Background Cloud Function to be triggered by Pub/Sub.
     * This function is exported by index.js, and executed when
     * the trigger topic receives a message.
     *
     * @param {object} message The Pub/Sub message.
     * @param {object} context The event metadata.
     */
    exports.helloPubSub = (message, context) => {
      const name = message.data
        ? Buffer.from(message.data, 'base64').toString()
        : 'World';
    
      console.log(`Hello, ${name}!`);
    };

    Python

    def hello_pubsub(event, context):
        """Background Cloud Function to be triggered by Pub/Sub.
        Args:
             event (dict):  The dictionary with data specific to this type of
                            event. The `@type` field maps to
                             `type.googleapis.com/google.pubsub.v1.PubsubMessage`.
                            The `data` field maps to the PubsubMessage data
                            in a base64-encoded string. The `attributes` field maps
                            to the PubsubMessage attributes if any is present.
             context (google.cloud.functions.Context): Metadata of triggering event
                            including `event_id` which maps to the PubsubMessage
                            messageId, `timestamp` which maps to the PubsubMessage
                            publishTime, `event_type` which maps to
                            `google.pubsub.topic.publish`, and `resource` which is
                            a dictionary that describes the service API endpoint
                            pubsub.googleapis.com, the triggering topic's name, and
                            the triggering event type
                            `type.googleapis.com/google.pubsub.v1.PubsubMessage`.
        Returns:
            None. The output is written to Cloud Logging.
        """
        import base64
    
        print(
            """This Function was triggered by messageId {} published at {} to {}
        """.format(
                context.event_id, context.timestamp, context.resource["name"]
            )
        )
    
        if "data" in event:
            name = base64.b64decode(event["data"]).decode("utf-8")
        else:
            name = "World"
        print(f"Hello {name}!")
    
    

    Go

    
    // Package helloworld provides a set of Cloud Functions samples.
    package helloworld
    
    import (
    	"context"
    	"log"
    )
    
    // PubSubMessage is the payload of a Pub/Sub event.
    // See the documentation for more details:
    // https://cloud.google.com/pubsub/docs/reference/rest/v1/PubsubMessage
    type PubSubMessage struct {
    	Data []byte `json:"data"`
    }
    
    // HelloPubSub consumes a Pub/Sub message.
    func HelloPubSub(ctx context.Context, m PubSubMessage) error {
    	name := string(m.Data) // Automatically decoded from base64.
    	if name == "" {
    		name = "World"
    	}
    	log.Printf("Hello, %s!", name)
    	return nil
    }
    

    Java

    
    import com.google.cloud.functions.BackgroundFunction;
    import com.google.cloud.functions.Context;
    import functions.eventpojos.PubsubMessage;
    import java.nio.charset.StandardCharsets;
    import java.util.Base64;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    
    public class HelloPubSub implements BackgroundFunction<PubsubMessage> {
      private static final Logger logger = Logger.getLogger(HelloPubSub.class.getName());
    
      @Override
      public void accept(PubsubMessage message, Context context) {
        String name = "world";
        if (message != null && message.getData() != null) {
          name = new String(
              Base64.getDecoder().decode(message.getData().getBytes(StandardCharsets.UTF_8)),
              StandardCharsets.UTF_8);
        }
        logger.info(String.format("Hello %s!", name));
        return;
      }
    }

    Ruby

    require "functions_framework"
    require "base64"
    
    FunctionsFramework.cloud_event "hello_pubsub" do |event|
      # The event parameter is a CloudEvents::Event::V1 object.
      # See https://cloudevents.github.io/sdk-ruby/latest/CloudEvents/Event/V1.html
      name = Base64.decode64 event.data["message"]["data"] rescue "World"
    
      # A cloud_event function does not return a response, but you can log messages
      # or cause side effects such as sending additional events.
      logger.info "Hello, #{name}!"
    end

Men-deploy fungsi

Untuk men-deploy fungsi dengan pemicu Pub/Sub, jalankan perintah berikut di direktori yang berisi kode contoh (atau untuk Java, file pom.xml):

Node.js

gcloud functions deploy helloPubSub \
--runtime nodejs22 \
--trigger-topic YOUR_TOPIC_NAME

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

Python

gcloud functions deploy hello_pubsub \
--runtime python312 \
--trigger-topic YOUR_TOPIC_NAME

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

Go

gcloud functions deploy HelloPubSub \
--runtime go121 \
--trigger-topic YOUR_TOPIC_NAME

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

Java

gcloud functions deploy java-pubsub-function \
--entry-point functions.HelloPubSub \
--runtime java17 \
--memory 512MB \
--trigger-topic YOUR_TOPIC_NAME

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

Ruby

gcloud functions deploy hello_pubsub --runtime ruby33 \
-
-trigger-topic YOUR_TOPIC_NAME

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

dengan YOUR_TOPIC_NAME adalah nama topik Pub/Sub yang akan menjadi langganan fungsi.

Jika YOUR_TOPIC_NAME belum ada, perintah ini akan membuatnya untuk Anda. Anda juga dapat membuat topik sebelum menjalankan perintah deploy, menggunakan konsolGoogle Cloud atau perintah gcloud berikut:

gcloud pubsub topics create YOUR_TOPIC_NAME

Memicu fungsi

  1. Publikasikan pesan ke topik Pub/Sub Anda. Dalam contoh ini, pesan adalah nama yang akan disertakan oleh fungsi dalam salam:

    gcloud pubsub topics publish YOUR_TOPIC_NAME --message YOUR_NAME

    Ganti YOUR_TOPIC_NAME dengan nama topik Pub/Sub Anda, dan YOUR_NAME dengan string arbitrer.

  2. Periksa log untuk memastikan eksekusi telah selesai:

    gcloud functions logs read --limit 50

Anda juga dapat memublikasikan pesan ke topik Pub/Sub dari dalam fungsi.