快速入门:使用 gcloud CLI 保护传入服务的流量

本页面介绍如何在 API Gateway 上部署 API 以保护流向后端服务的流量。

请按照以下步骤使用 Google Cloud CLI 部署新的 API 以访问 Cloud Run functions 上的后端服务。本快速入门还介绍了如何使用 API 密钥保护您的后端免遭未经授权的访问。

准备工作

  1. 在 Google Cloud 控制台中,前往信息中心页面,然后选择或创建 Google Cloud 项目。

    转到信息中心

  2. 确认您的项目已启用结算功能。

    启用结算功能

  3. 确认 Google Cloud CLI 已下载并安装到您的机器上。

    下载 gcloud CLI

  4. 更新 gcloud 组件:

    gcloud components update
  5. 设置默认项目。请将 PROJECT_ID 替换为您的 Google Cloud 项目 ID。

    gcloud config set project PROJECT_ID

启用必需服务

API Gateway 要求您启用以下 Google Cloud 服务:

名称 服务名称
API Gateway API apigateway.googleapis.com
Service Management API servicemanagement.googleapis.com
Service Control API servicecontrol.googleapis.com

如需启用必需的服务,请执行以下操作:

Google Cloud 控制台

  1. 在 Google Cloud 控制台中,前往 API 和服务 > API 库页面。

    前往 API 库

  2. API 库页面上,在搜索栏中输入所需的 API 名称。
  3. 在搜索结果中,选择 API 页面。
  4. 在 API 页面上,点击启用
  5. 针对上表中列出的每项服务重复上述步骤。

Google Cloud CLI

使用以下命令启用服务:

gcloud services enable apigateway.googleapis.com
gcloud services enable servicemanagement.googleapis.com
gcloud services enable servicecontrol.googleapis.com

如需详细了解 gcloud 服务,请参阅 gcloud 服务

部署 API 后端

API Gateway 位于已部署后端服务的前面,负责处理所有传入请求。在本快速入门中,API Gateway 会将传入的调用路由到名为 helloGET 的 Cloud Run 函数后端,该后端包含如下所示的 Node.js 函数。

const functions = require('@google-cloud/functions-framework');

// Register an HTTP function with the Functions Framework that will be executed
// when you make an HTTP request to the deployed function's endpoint.
functions.http('helloGET', (req, res) => {
  res.send('Hello World!');
});

按照快速入门:使用 Google Cloud CLI 部署 Cloud Run 函数中的步骤下载示例 Cloud Run 函数代码并部署 Cloud Run 函数后端服务。您的管理员需要按照此快速入门中的说明,向您的账号和 Cloud Build 服务账号授予其他角色。

复制 Cloud Run 函数部署完成后显示的服务网址。您需要在后续步骤中创建 API 配置时使用此值。

创建 API

现在,您可以在 API Gateway 上创建 API 了。

  1. 输入以下命令,其中:

    • API_ID 指定 API 的名称。请参阅 API ID 要求,了解 API 命名准则。
      gcloud api-gateway apis create API_ID 

    例如:

    gcloud api-gateway apis create my-api
  2. 成功完成后,您可以使用以下命令查看有关新 API 的详细信息:

    gcloud api-gateway apis describe API_ID 

    例如:

    gcloud api-gateway apis describe my-api 

    此命令会返回以下内容:

      createTime: '2020-02-29T21:52:20.297426875Z'
      displayName: my-api
      managedService: my-api-123abc456def1.apigateway.my-project.cloud.goog
      name: projects/my-project/locations/global/apis/my-api
      state: ACTIVE
      updateTime: '2020-02-29T21:52:20.647923711Z'

复制 managedService 属性的值。此值用于在后续步骤中启用您的 API。

创建 API 配置

您需要 API 配置,才能使用 API Gateway 来管理发送到已部署的 API 后端的流量。

您可以使用包含专用注释的 OpenAPI 说明来创建 API 配置,以定义所选的 API Gateway 行为。如需详细了解支持的 OpenAPI 扩展程序,请参阅以下内容:

本快速入门中使用的 OpenAPI 说明包含在我们的 Cloud Run 函数后端的路由说明:

OpenAPI 2.0

# openapi-functions.yaml
swagger: '2.0'
info:
  title: API_ID optional-string
  description: Sample API on API Gateway with a Google Cloud Functions backend
  version: 1.0.0
schemes: