将事件发布到 Cloud Run 作业
本快速入门介绍了如何在 Google Cloud项目中创建 Eventarc Advanced 总线并进行注册,从而发布和接收事件消息。
总线充当中央路由器,接收来自事件源或提供方发布的消息。
注册通过处理流水线将总线接收到的消息路由到一个或多个目的地。
在本快速入门中,您将执行以下操作:
从源代码部署 Cloud Run 作业。
创建 Eventarc Advanced 总线。
创建 Eventarc Advanced 注册。
向总线发布事件消息。
确认 Cloud Run 作业已成功执行。
您可以使用 gcloud CLI 完成本快速入门。
准备工作
您的组织定义的安全限制条件可能会导致您无法完成以下步骤。如需了解相关问题排查信息,请参阅在受限的 Google Cloud 环境中开发应用。
- 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.
-
Install the Google Cloud CLI.
-
如果您使用的是外部身份提供方 (IdP),则必须先使用联合身份登录 gcloud CLI。
-
如需初始化 gcloud CLI,请运行以下命令:
gcloud init -
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 role
(
roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.createpermission. Learn how to grant roles.
-
Create a Google Cloud project:
gcloud projects create PROJECT_ID
Replace
PROJECT_IDwith 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_IDwith your Google Cloud project name.
-
Verify that billing is enabled for your Google Cloud project.
-
Enable the Artifact Registry, Cloud Build, 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 theserviceusage.services.enablepermission. Learn how to grant roles.gcloud services enable artifactregistry.googleapis.com
cloudbuild.googleapis.com eventarc.googleapis.com eventarcpublishing.googleapis.com run.googleapis.com -
Install the Google Cloud CLI.
-
如果您使用的是外部身份提供方 (IdP),则必须先使用联合身份登录 gcloud CLI。
-
如需初始化 gcloud CLI,请运行以下命令:
gcloud init -
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 role
(
roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.createpermission. Learn how to grant roles.
-
Create a Google Cloud project:
gcloud projects create PROJECT_ID
Replace
PROJECT_IDwith 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_IDwith your Google Cloud project name.
-
Verify that billing is enabled for your Google Cloud project.
-
Enable the Artifact Registry, Cloud Build, 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 theserviceusage.services.enablepermission. Learn how to grant roles.gcloud services enable artifactregistry.googleapis.com
cloudbuild.googleapis.com eventarc.googleapis.com eventarcpublishing.googleapis.com run.googleapis.com - 更新
gcloud组件:gcloud components update
- 使用您的账号登录:
gcloud auth login
- 设置本快速入门中使用的配置变量:
REGION=REGION
将
REGION替换为总线的受支持位置,例如us-central1。 -
如果您是项目创建者,则会被授予基本 Owner 角色 (
roles/owner)。默认情况下,此 Identity and Access Management (IAM) 角色可提供完全访问大多数 Google Cloud资源所需的权限,您可以跳过此步骤。如果您不是项目创建者,则必须向主账号授予项目的必需权限。例如,主账号可以是 Google 账号(针对最终用户)或服务账号(针对应用和计算工作负载)。
所需权限
如需获得完成本快速入门所需的权限,请让您的管理员为您授予项目的以下 IAM 角色:
-
Cloud Run Developer (
roles/run.developer) -
Eventarc Developer (
roles/eventarc.developer) -
Eventarc Message Bus Admin (
roles/eventarc.messageBusAdmin) -
Logs View Accessor (
roles/logging.viewAccessor) -
Project IAM Admin (
roles/resourcemanager.projectIamAdmin) -
Service Account Admin (
roles/iam.serviceAccountAdmin) -
Service Account User (
roles/iam.serviceAccountUser) -
Service Usage Admin (
roles/serviceusage.serviceUsageAdmin)
如需详细了解如何授予角色,请参阅管理对项目、文件夹和组织的访问权限。
-
Cloud Run Developer (
- 如需向 Eventarc 高级版授予执行 Cloud Run 作业所需的权限,请让管理员向您的Google Cloud 项目中的服务账号授予 Cloud Run Invoker (
roles/run.invoker) IAM 角色:- 创建一个服务账号。为了进行测试,您将此服务账号附加到 Eventarc Advanced 流水线以表示该流水线的身份。
将gcloud iam service-accounts create SERVICE_ACCOUNT_NAME
SERVICE_ACCOUNT_NAME替换为您的服务账号的名称。 - 向服务账号授予
roles/run.invokerIAM 角色:gcloud projects add-iam-policy-binding PROJECT_ID \ --member="serviceAccount:SERVICE_ACCOUNT_NAME@PROJECT_ID.iam.gserviceaccount.com" \ --role=roles/run.invoker
- 创建一个服务账号。为了进行测试,您将此服务账号附加到 Eventarc Advanced 流水线以表示该流水线的身份。
创建名为
jobs的目录并导航至该目录:mkdir jobs cd jobs创建一个
main.py文件,并将以下示例代码复制到其中:import os TASK_INDEX = os.getenv("CLOUD_RUN_TASK_INDEX", 0) def main(): """ This job prints "Hello world" """ print(f"Starting task #{TASK_INDEX}...") print("Hello world") print(f"Completed task #{TASK_INDEX}.") # Start script if __name__ == "__main__": main()创建一个名为
Procfile且无文件扩展名的文本文件,并将以下文本复制到其中:web: python3 main.py部署作业:
gcloud run jobs deploy JOB_NAME \ --source . \ --tasks 1 \ --region=$REGION
将
JOB_NAME替换为 Cloud Run 作业的唯一名称,例如my-job。使用
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 时使用。
使用
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 logging read命令过滤日志条目并返回输出:gcloud logging read 'textPayload: "Hello world"'
查找如下日志条目:
insertId: 693c8dd0000cb2976d7966b8 ... labels: job_name: JOB_NAME location: REGION project_id: PROJECT_ID type: cloud_run_job textPayload: Hello world timestamp: '2025-12-12T21:49:04.832151Z'您还可以使用
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 资源:
从源代码部署 Cloud Run 作业
将 Cloud Run 作业部署为事件目标。与侦听和处理请求的 Cloud Run 服务不同,Cloud Run 作业仅运行其任务并在完成后退出。作业不会监听或处理请求。
系统还支持其他事件目标位置,例如 Pub/Sub 主题、Workflows 或其他 HTTP 端点。如需了解详情,请参阅事件提供方和目的地。
使用 gcloud run jobs deploy 命令从 Python 源代码创建作业。您的代码会自动打包到容器映像中,上传到 Artifact Registry,然后部署到 Cloud Run。
创建 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 时,您首先要创建流水线,然后再创建注册:
向总线发布事件消息
如需直接向总线发布消息,请使用 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 高级总线后,检查 Cloud Run 作业的日志,验证 Cloud Run 作业是否已成功执行,以及是否已打印“Hello world”。作业可能需要几分钟时间才能运行并完成。
您已成功创建 Eventarc Advanced 总线和注册,向总线发布事件消息,并在事件接收器的日志中验证预期结果。
清理
为避免在完成此快速入门后继续计费,请删除您创建的资源:或者,您也可以删除 Google Cloud 项目,以避免产生费用。 删除 Google Cloud 项目后,系统即会停止对该项目中使用的所有资源计费。
Delete a Google Cloud project:
gcloud projects delete PROJECT_ID