Cloud Pub/Sub 教學課程 (第 1 代)


本簡單教學課程將示範如何使用 Pub/Sub 觸發程序,編寫、部署及觸發事件驅動型 Cloud Run 函式

如果您是 Pub/Sub 新手,想進一步瞭解相關資訊,請參閱 Pub/Sub 說明文件,特別是管理主題和訂閱項目。如要瞭解如何在 Cloud Run 函式中使用 Pub/Sub 主題和訂閱項目,請參閱「Pub/Sub 觸發條件」一文。

如要尋找使用 Pub/Sub 本身的程式碼範例,請前往範例瀏覽器

目標

費用

在本文件中,您會使用 Google Cloud的下列計費元件:

  • Cloud Run functions
  • Pub/Sub

如要根據預測用量估算費用,請使用 Pricing Calculator

初次使用 Google Cloud 的使用者可能符合免費試用資格。

事前準備

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  3. Make sure that billing is enabled for your Google Cloud project.

  4. Enable the Cloud Functions and Cloud Pub/Sub APIs.

    Enable the APIs

  5. Install the Google Cloud CLI.

  6. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  7. To initialize the gcloud CLI, run the following command:

    gcloud init
  8. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  9. Make sure that billing is enabled for your Google Cloud project.

  10. Enable the Cloud Functions and Cloud Pub/Sub APIs.

    Enable the APIs

  11. Install the Google Cloud CLI.

  12. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  13. To initialize the gcloud CLI, run the following command:

    gcloud init
  14. 如果您已安裝 gcloud CLI,請執行下列指令來更新:

    gcloud components update
  15. 準備開發環境。 <0x

準備應用程式

  1. 將應用程式存放區範例複製到本機電腦中:

    Node.js

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

    您也可以 下載 zip 格式的範例,然後解壓縮該檔案。

    Python

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

    您也可以 下載 zip 格式的範例,然後解壓縮該檔案。

    Go

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

    您也可以 下載 zip 格式的範例,然後解壓縮該檔案。

    Java

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

    您也可以 下載 zip 格式的範例,然後解壓縮該檔案。

    Ruby

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

    您也可以 下載 zip 格式的範例,然後解壓縮該檔案。

  2. 變更為包含 Cloud Run 函式範例程式碼的目錄,以存取 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. 查看程式碼範例:

    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

部署函式

如要使用 Pub/Sub 觸發條件部署函式,請在包含範例程式碼的目錄中執行下列指令 (如果是 Java,則在 pom.xml 檔案中執行):

Node.js

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

使用 --runtime 標記指定支援的 Node.js 版本執行階段 ID,以執行函式。

Python

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

使用 --runtime 標記指定支援的 Python 版本執行階段 ID,以執行函式。

Go

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

使用 --runtime 標記指定支援的 Go 版本執行階段 ID,以執行函式。

Java

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

使用 --runtime 標記指定支援的 Java 版本執行函式的執行階段 ID。

Ruby

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

使用 --runtime 標記指定支援的 Ruby 版本執行階段 ID,以執行函式。

其中 YOUR_TOPIC_NAME 是函式要訂閱的 Pub/Sub 主題名稱。

如果 YOUR_TOPIC_NAME 不存在,這項指令會為您建立。您也可以在執行 deploy 指令前,使用Google Cloud 主控台或下列 gcloud 指令建立主題:

gcloud pubsub topics create YOUR_TOPIC_NAME

觸發函式

  1. 將訊息發布至 Pub/Sub 主題。在本例中,訊息是函式會在問候語中加入的名稱:

    gcloud pubsub topics publish YOUR_TOPIC_NAME --message YOUR_NAME

    YOUR_TOPIC_NAME 替換為 Pub/Sub 主題名稱,並將 YOUR_NAME 替換為任意字串。

  2. 檢查記錄以確定執行已經完成:

    gcloud functions logs read --limit 50

您也可以從函式內部將訊息發布至 Pub/Sub 主題。

清除所用資源

如要避免系統向您的 Google Cloud 帳戶收取本教學課程中所用資源的相關費用,請刪除含有該項資源的專案,或者保留專案但刪除個別資源。

刪除專案

如要避免付費,最簡單的方法就是刪除您為了本教學課程所建立的專案。

如要刪除專案:

  1. In the Google Cloud console, go to the Manage resources page.

    Go to Manage resources

  2. In the project list, select the project that you want to delete, and then click Delete.
  3. In the dialog, type the project ID, and then click Shut down to delete the project.

刪除函式

刪除 Cloud Run 函式不會移除儲存在 Cloud Storage 中的任何資源。

如要刪除您在本教學課程中建立的函式,請執行下列指令:

Node.js

gcloud functions delete helloPubSub 

Python

gcloud functions delete hello_pubsub 

Go

gcloud functions delete HelloPubSub 

Java

gcloud functions delete java-pubsub-function 

Ruby

gcloud functions delete hello_pubsub 

您也可以從 Google Cloud 控制台刪除 Cloud Run 函式。