通过创建总线和注册来发布和接收事件 (gcloud CLI)
本快速入门介绍了如何通过在 Google Cloud项目中创建 Eventarc Advanced 总线并进行注册来发布和接收事件消息。
- 借助总线,您可以集中管理系统中的消息流,并将其用作路由器。它会从消息来源或提供方接收事件消息,并根据注册信息评估这些消息。 
- 注册会标识对特定总线的订阅,并定义消息的匹配条件,从而使消息能够相应地路由到一个或多个目的地。 
在本快速入门中,您将执行以下操作:
- 创建 Artifact Registry 标准制品库。 
- 将事件接收器服务部署到 Cloud Run。 
- 创建 Eventarc Advanced 总线。 
- 创建 Eventarc Advanced 注册。 
- 向总线发布事件消息。 
- 在 Cloud Run 日志中查看事件数据。 
您可以使用 gcloud CLI 完成本快速入门。如需使用 Google Cloud 控制台完成这些步骤,请参阅通过创建总线和注册来发布和接收事件(控制台)。
准备工作
您的组织定义的安全限制条件可能会导致您无法完成以下步骤。如需了解相关问题排查信息,请参阅在受限的 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
      (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, Compute Engine, 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 compute.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
      (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, Compute Engine, 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 compute.googleapis.com eventarc.googleapis.com eventarcpublishing.googleapis.com run.googleapis.com 
- 更新 gcloud组件:gcloud components update 
- 使用您的账号登录:gcloud auth login 
- 设置本快速入门中使用的配置变量:
REGION=REGION 将 REGION替换为总线的受支持位置。
- 
如果您是项目创建者,则会被授予基本 Owner 角色 ( roles/owner)。默认情况下,此 Identity and Access Management (IAM) 角色可提供完全访问大多数 Google Cloud资源所需的权限,您可以跳过此步骤。如果您不是项目创建者,则必须向主账号授予项目的必需权限。例如,主账号可以是 Google 账号(针对最终用户)或服务账号(针对应用和计算工作负载)。 请注意,默认情况下,Cloud Build 权限包含上传和下载 Artifact Registry 工件的权限。 所需权限如需获得完成本快速入门所需的权限,请让您的管理员为您授予项目的以下 IAM 角色: - 
  
  
    
      Cloud Build Editor  (roles/cloudbuild.builds.editor)
- 
  
  
    
      Cloud Run Admin  (roles/run.admin)
- 
  
  
    
      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 Build Editor  (
- 向 Compute Engine 默认服务账号授予项目的以下角色。构建和部署容器映像时需要以下角色:
- Artifact Registry Writer:用于上传 Artifact Registry 制品
- Logs Writer:将日志写入 Cloud Logging
- Storage Object User:用于访问 Cloud Storage 对象
 gcloud projects add-iam-policy-binding PROJECT_ID \ --member=serviceAccount:PROJECT_NUMBER-compute@developer.gserviceaccount.com \ --role=roles/artifactregistry.writer gcloud projects add-iam-policy-binding PROJECT_ID \ --member=serviceAccount:PROJECT_NUMBER-compute@developer.gserviceaccount.com \ --role=roles/logging.logWriter gcloud projects add-iam-policy-binding PROJECT_ID \ --member=serviceAccount:PROJECT_NUMBER-compute@developer.gserviceaccount.com \ --role=roles/storage.objectUser 将 PROJECT_NUMBER替换为您的 Google Cloud项目编号。您可以在 Google Cloud 控制台的欢迎页面上,或通过运行以下命令来查找项目编号:gcloud projects describe PROJECT_ID --format='value(projectNumber)' 
- 默认情况下,只有 Project Owner、Project Editor 以及 Cloud Run Admin 和 Invoker 可以调用 Cloud Run 服务。如需设置身份验证,请向服务账号授予 Google Cloud 项目的 Cloud Run Invoker 角色 (run.invoker):- 创建一个服务账号。为了进行测试,您会将此服务账号附加到 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 
 请注意,您可以通过以下任一方式配置谁可以访问您的 Cloud Run 服务: - 向选定的服务账号或群组授予此权限,以允许访问服务。所有请求都必须具有 HTTP 授权标头,其中包含由 Google 为其中一个已获授权的服务账号签名的 OpenID Connect 令牌。本快速入门中就是通过这种方式配置访问权限的。
- 向 allUsers授予此权限,以允许未经身份验证的访问。
 如需了解详情,请参阅 Cloud Run 的访问权限控制。 
- 创建一个服务账号。为了进行测试,您会将此服务账号附加到 Eventarc Advanced 流水线,以表示该流水线的身份。
- 克隆 GitHub 代码库: - git clone https://github.com/GoogleCloudPlatform/eventarc-samples.git 
- 切换到包含 Cloud Run 示例代码的目录: - cd eventarc-samples/eventarc-advanced-quickstart/ 
- 构建 Docker 容器映像并将该映像推送到您的代码库: - gcloud builds submit \ --tag $REGION-docker.pkg.dev/PROJECT_ID/REPOSITORY/log-events:v1 
- 将容器映像部署到 Cloud Run: - gcloud run deploy SERVICE_NAME \ --image $REGION-docker.pkg.dev/PROJECT_ID/REPOSITORY/log-events:v1 \ --platform managed \ --ingress all \ --no-allow-unauthenticated \ --region=$REGION - 将 - SERVICE_NAME替换为您的服务名称,例如- my-service。- all的入站流量设置允许所有请求,包括直接从互联网发送到- run.app网址的请求。如需了解详情,请参阅限制 Cloud Run 的网络入站流量。- --no-allow-unauthenticated标志将服务配置为仅允许经过身份验证的调用。
- 使用 - gcloud eventarc pipelines create命令创建流水线:- gcloud eventarc pipelines create PIPELINE_NAME \ --destinations=http_endpoint_uri='CLOUD_RUN_SERVICE_URL',google_oidc_authentication_service_account=SERVICE_ACCOUNT_NAME@PROJECT_ID.iam.gserviceaccount.com \ --location=$REGION - 替换以下内容: - PIPELINE_NAME:流水线的 ID 或完全限定名称。
- CLOUD_RUN_SERVICE_URL:Cloud Run 服务的完全限定网址,例如- https://SERVICE_NAME-abcdef-uc.a.run.app。这是事件消息的目标位置。
 - 请注意, - google_oidc_authentication_service_account键指定了一个服务账号电子邮件地址,该地址用于生成 OIDC 令牌。
- 使用 - 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 或完全限定名称。
- MATCH_EXPRESSION:此注册的匹配表达式(使用 CEL)- 例如:- "message.type == 'hello-world-type'"
 
- 使用 - gcloud logging read命令过滤日志条目并返回输出:- gcloud logging read 'textPayload: "hello-world-data"' 
- 查找如下日志条目: - insertId: 670808e70002b5c6477709ae labels: instanceId: 007989f2a10a4a33c21024f2c8e06a9de65d9b4fdc2ee27697a50379b3fab2f975b9233dc357d50b06270829b9b479d5a1ee54a10fa2cb2d98c5f77a0895e2be0f9e6e4b20 logName: projects/PROJECT_ID/logs/run.googleapis.com%2Fstderr receiveTimestamp: '2024-10-10T17:03:35.424659450Z' resource: labels: ... type: cloud_run_revision textPayload: "[2024-10-21 15:33:19,581] INFO in server: Body: b'{\"value\":\"hello-world-data\"\ }'" timestamp: '2024-10-10T17:03:35.177606Z'
- 删除 Eventarc Advanced 资源: 
创建 Artifact Registry 标准制品库
创建 Artifact Registry 标准制品库以存储您的容器映像。
gcloud artifacts repositories create REPOSITORY \ --repository-format=docker \ --location=$REGION
将 REPOSITORY 替换为 Artifact Registry 制品库的唯一名称,例如 my-repo。
将事件接收器服务部署到 Cloud Run
部署记录事件内容的 Cloud Run 服务。系统还支持其他事件目标,例如 Pub/Sub 主题、Workflows 或 HTTP 端点。如需了解详情,请参阅事件提供方和目的地。
当您看到 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 注册
注册可确定哪些消息会路由到目的地,还会指定用于为事件消息配置目的地的流水线。
如需了解详情,请参阅创建注册以接收活动。
使用 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 Advanced 总线后,您可以检查 Cloud Run 服务的日志,验证事件是否按预期接收。
您已成功创建 Eventarc Advanced 总线和注册,向总线发布事件消息,并在事件接收器服务的日志中验证预期结果。
清理
完成此快速入门中描述的任务后,您可以通过删除所创建的资源来避免继续计费:
或者,您也可以删除 Google Cloud 项目,以避免产生费用。删除 Google Cloud 项目后,系统即会停止对该项目中使用的所有资源计费。
Delete a Google Cloud project:
gcloud projects delete PROJECT_ID