將事件發布至 Cloud Run 工作

本快速入門導覽課程說明如何透過在 Google Cloud專案中建立 Eventarc Advanced 匯流排和註冊項目,發布及接收事件訊息。

  • 匯流排可做為中央路由器,接收來自事件來源的訊息,或由提供者發布的訊息。

  • 註冊會透過處理管道,將匯流排收到的訊息轉送至一或多個目的地。

在本快速入門導覽課程中,您將:

  1. 部署 Cloud Run 工作。

  2. 建立 Eventarc Advanced 匯流排。

  3. 建立 Eventarc Advanced 註冊。

  4. 將事件訊息發布至匯流排。

  5. 查看記錄中的事件資料,確認 Cloud Run 工作已順利執行。

您可以使用 gcloud CLI 完成本快速入門導覽課程。

事前準備

貴機構定義的安全性限制,可能會導致您無法完成下列步驟。如需疑難排解資訊,請參閱「在受限的 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. Install the Google Cloud CLI.

  3. 如果您使用外部識別資訊提供者 (IdP),請先 使用聯合身分登入 gcloud CLI

  4. 如要初始化 gcloud CLI,請執行下列指令:

    gcloud init
  5. Create or select a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.
    • Create a Google Cloud project:

      gcloud projects create PROJECT_ID

      Replace PROJECT_ID with a name for the Google Cloud project you are creating.

    • Select the Google Cloud project that you created:

      gcloud config set project PROJECT_ID

      Replace PROJECT_ID with your Google Cloud project name.

  6. Verify that billing is enabled for your Google Cloud project.

  7. Enable the Cloud Run and Eventarc APIs:

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    gcloud services enable eventarc.googleapis.com eventarcpublishing.googleapis.com run.googleapis.com 
  8. Install the Google Cloud CLI.

  9. 如果您使用外部識別資訊提供者 (IdP),請先 使用聯合身分登入 gcloud CLI

  10. 如要初始化 gcloud CLI,請執行下列指令:

    gcloud init
  11. Create or select a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.
    • Create a Google Cloud project:

      gcloud projects create PROJECT_ID

      Replace PROJECT_ID with a name for the Google Cloud project you are creating.

    • Select the Google Cloud project that you created:

      gcloud config set project PROJECT_ID

      Replace PROJECT_ID with your Google Cloud project name.

  12. Verify that billing is enabled for your Google Cloud project.

  13. Enable the Cloud Run and Eventarc APIs:

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    gcloud services enable eventarc.googleapis.com eventarcpublishing.googleapis.com run.googleapis.com 
  14. 更新 gcloud 元件:
    gcloud components update
  15. 登入帳戶:
    gcloud auth login
  16. 設定本快速入門導覽課程中使用的設定變數:
    REGION=REGION

    REGION 替換為公車的支援位置,例如 us-central1

  17. 如果您是專案建立者,系統會授予基本「擁有者」角色 (roles/owner)。根據預設,這個身分與存取權管理 (IAM) 角色包含完全存取大多數 Google Cloud資源所需的權限,因此您可以略過這個步驟。

    如果您不是專案建立者,必須在專案中將必要權限授予適當的主體。舉例來說,主體可以是 Google 帳戶 (適用於使用者) 或服務帳戶 (適用於應用程式和運算工作負載)。

    所需權限

    如要取得完成本快速入門所需的權限,請要求管理員為您授予專案的下列 IAM 角色:

    如要進一步瞭解如何授予角色,請參閱「管理專案、資料夾和機構的存取權」。

    您或許還可透過自訂角色或其他預先定義的角色取得必要權限。

  18. 如要授予 Eventarc Advanced 執行 Cloud Run 作業的必要權限,請管理員在Google Cloud 專案中,將 Cloud Run Invoker (roles/run.invoker) IAM 角色授予服務帳戶:
    1. 建立服務帳戶。為進行測試,您會將這個服務帳戶附加至 Eventarc Advanced 管道,代表管道的身分。
      gcloud iam service-accounts create SERVICE_ACCOUNT_NAME
      SERVICE_ACCOUNT_NAME 替換為服務帳戶的名稱。
    2. roles/run.invoker 身分與存取權管理角色授予服務帳戶:
      gcloud projects add-iam-policy-binding PROJECT_ID \
          --member="serviceAccount:SERVICE_ACCOUNT_NAME@PROJECT_ID.iam.gserviceaccount.com" \
          --role=roles/run.invoker
  19. 部署 Cloud Run 工作

    Cloud Run 工作部署為事件目的地。Cloud Run 服務會監聽及處理要求,但 Cloud Run 工作只會執行工作,完成後就會結束。工作不會監聽或處理要求。

    系統支援其他事件目的地,例如 Pub/Sub 主題、Workflows 或其他 HTTP 端點。詳情請參閱「事件供應商和目的地」。

    使用 gcloud run jobs deploy 指令,從範例容器部署工作。

    gcloud run jobs deploy JOB_NAME --image us-docker.pkg.dev/cloudrun/container/job:latest \
        --region=$REGION

    JOB_NAME 替換為 Cloud Run 工作的專屬名稱,例如 my-job

    建立 Eventarc Advanced 匯流排

    匯流排會接收來自訊息來源或提供者發布的事件訊息,並做為訊息路由器。

    詳情請參閱建立用於傳送訊息的匯流排

    使用 gcloud eventarc message-buses create 指令,在專案中建立 Eventarc Advanced 匯流排:

    gcloud eventarc message-buses create BUS_NAME \
        --location=$REGION

    BUS_NAME 替換為匯流排的 ID 或完整名稱,例如 my-bus

    建立 Eventarc Advanced 註冊

    註冊會決定哪些訊息要轉送至目的地。此外,這個欄位也會指定用於設定事件訊息目的地的管道。在本例中,目標目的地是 Cloud Run 工作。

    詳情請參閱「建立註冊項目以接收事件」。

    使用 gcloud CLI 時,您會先建立管道,然後建立註冊:

    1. 使用 gcloud eventarc pipelines create 指令建立管道:

      gcloud eventarc pipelines create PIPELINE_NAME \
          --destinations=http_endpoint_uri='https://REGION-run.googleapis.com/apis/run.googleapis.com/v1/namespaces/PROJECT_NUMBER/jobs/JOB_NAME:run',http_endpoint_message_binding_template='{"body": ""}',oauth_token_authentication_service_account=SERVICE_ACCOUNT_NAME@PROJECT_ID.iam.gserviceaccount.com \
          --input-payload-format-json= \
          --location=$REGION

      更改下列內容:

      • PIPELINE_NAME:管道的 ID 或完整名稱,例如 my-pipeline
      • PROJECT_NUMBER:您的 Google Cloud 專案編號。您可以執行下列指令來擷取專案編號:
      gcloud projects describe PROJECT_ID --format='value(projectNumber)'

      注意事項:

      • http_endpoint_message_binding_template 鍵會將事件轉換為 Cloud Run Admin API 預期的格式。定義訊息繫結時,您必須設定輸入格式,才能存取酬載。
      • oauth_token_authentication_service_account 鍵會指定服務帳戶電子郵件地址。這封電子郵件會用於產生 OAuth 權杖,通常只會在呼叫 *.googleapis.com 上託管的 Google API 時使用。
    2. 使用 gcloud eventarc enrollments create 指令建立註冊:

      gcloud eventarc enrollments create ENROLLMENT_NAME \
          --cel-match=MATCH_EXPRESSION \
          --destination-pipeline=PIPELINE_NAME \
          --message-bus=BUS_NAME \
          --message-bus-project=PROJECT_ID \
          --location=$REGION

      更改下列內容:

      • ENROLLMENT_NAME:註冊 ID 或完整名稱,例如 my-enrollment
      • MATCH_EXPRESSION:這個註冊項目的比對運算式 (使用 CEL),例如:

        "message.type == 'hello-world-type'"
        

    將事件訊息發布至匯流排

    如要直接將訊息發布至匯流排,請使用 gcloud eventarc message-buses publish 指令,或向 Eventarc Publishing REST API 傳送要求。詳情請參閱「直接發布事件」。

    訊息必須採用 CloudEvents 格式,這是以通用方式描述事件資料的規格。data 元素是事件的酬載。這個欄位可接受任何格式正確的 JSON。如要進一步瞭解 CloudEvents 內容屬性,請參閱「事件格式」。

    以下範例說明如何直接將事件發布至 Eventarc Advanced 匯流排:

    範例 1

    使用 gcloud CLI 和 --event-data 及其他事件屬性標記,將事件發布至匯流排:

    gcloud eventarc message-buses publish BUS_NAME \
        --event-data='{"key": "hello-world-data"}' \
        --event-id=hello-world-id-1234 \
        --event-source=hello-world-source \
        --event-type=hello-world-type \
        --event-attributes="datacontenttype=application/json" \
        --location=$REGION
    

    範例 2

    使用 gcloud CLI 和 --json-message 旗標,以 JSON 訊息的形式將事件發布至匯流排:

    gcloud eventarc message-buses publish BUS_NAME \
        --location=$REGION \
        --json-message='{"id": "hello-world-id-1234", "type":
     "hello-world-type", "source":
     "hello-world-source", "specversion": "1.0", "data":
     {"key": "hello-world-data"}}'
    

    發布活動後,您應該會收到「活動發布成功」訊息。

    在 Cloud Run 記錄中查看事件資料

    將事件發布至 Eventarc Advanced 匯流排後,請檢查 Cloud Run 工作的記錄檔,確認事件是否如預期收到。

    1. 使用 gcloud logging read 指令篩選記錄項目並傳回輸出內容:

      gcloud logging read 'textPayload: "hello-world-data"'
      
    2. 尋找類似下列內容的記錄項目:

      insertId: 670808e70002b5c6477709ae
      labels:
      instanceId: 007989f2a10a4a33c21024f2c8e06a9de65d9b4fdc2ee27697a50379b3fab2f975b9233dc357d50b06270829b9b479d5a1ee54a10fa2cb2d98c5f77a0895e2be0f9e6e4b20
      logName: projects/PROJECT_ID/logs/run.googleapis.com%2Fstderr
      receiveTimestamp: '2025-10-06T21:15:22.988264020Z'
      resource:
      labels:
      ...
      type: cloud_run_revision
      textPayload: "[2025-10-06 21:15:22,676] INFO in server: Body: b'{\"key\": \"hello-world-data\"\
        }'"
      timestamp: '2025-10-06T21:15:22.675530Z'
      
    3. 使用 gcloud run jobs describe 指令,確認 Cloud Run 工作是否成功執行:

      gcloud run jobs describe JOB_NAME \
          --region=$REGION
      

      您會看到類似下方的輸出內容:

      ✔ Job JOB_NAME in region us-central1
      Executed 1 time
      ...
      

    您已成功建立 Eventarc Advanced 匯流排和註冊項目、將事件訊息發布至匯流排,並在事件接收器的記錄中驗證預期結果。

    清除所用資源

    為避免在完成本快速入門導覽課程後繼續計費,請刪除您建立的資源:

    1. 刪除 Cloud Run 工作

    2. 刪除 Eventarc Advanced 資源:

      1. 刪除註冊項目

      2. 刪除管道

      3. 刪除匯流排

    或者,刪除專案,以免產生費用。 Google Cloud 刪除 Google Cloud 專案後,系統就會停止對專案使用的所有資源收取費用。

    Delete a Google Cloud project:

    gcloud projects delete PROJECT_ID

    後續步驟