将事件发布到 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. 如果您是项目创建者,则会被授予基本 Owner 角色 (roles/owner)。默认情况下,此 Identity and Access Management (IAM) 角色可提供完全访问大多数 Google Cloud资源所需的权限,您可以跳过此步骤。

    如果您不是项目创建者,则必须向主账号授予项目的必需权限。例如,主账号可以是 Google 账号(针对最终用户)或服务账号(针对应用和计算工作负载)。

    所需权限

    如需获得完成本快速入门所需的权限,请让您的管理员为您授予项目的以下 IAM 角色:

    如需详细了解如何授予角色,请参阅管理对项目、文件夹和组织的访问权限

    您也可以通过自定义角色或其他预定义角色来获取所需的权限。

  18. 如需向 Eventarc 高级版授予执行 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 IAM 角色:
      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

    后续步骤