使用 Google Cloud Functions 实现微服务的 API 网关

2024-04-22

Inputs

例如,我们有一些服务。

  1. 账户服务
  2. 产品服务
  3. 支付服务

每项服务都是一个单独的 Google Cloud Function。 每个服务都有自己的 HTTP API。例如,账户服务有:

  1. https://REGION-FUNCTIONS_PROJECT_ID.cloudfunctions.net/account/sign-up https://REGION-FUNCTIONS_PROJECT_ID.cloudfunctions.net/account/sign-up
  2. https://REGION-FUNCTIONS_PROJECT_ID.cloudfunctions.net/account/sign-in https://REGION-FUNCTIONS_PROJECT_ID.cloudfunctions.net/account/sign-in
  3. https://REGION-FUNCTIONS_PROJECT_ID.cloudfunctions.net/account/reset-password https://REGION-FUNCTIONS_PROJECT_ID.cloudfunctions.net/account/reset-password
  4. etc

每个服务都有自己的 swagger 文档端点/docs.

Question

如何将我的云函数设为私有(无需公共访问)并将它们放置在某个 API 网关后面?

Notes

Google 提供了 Cloud Functions 端点(请参阅https://cloud.google.com/endpoints/docs/openapi/get-started-cloud-functions https://cloud.google.com/endpoints/docs/openapi/get-started-cloud-functions)。 但是,据我了解,Endpoints 允许您仅定义 yaml OpenAPI 文件。

在此 yaml 文件中,我可以定义如下内容:

swagger: '2.0'
info:
  title: Cloud Endpoints + GCF
  description: Sample API on Cloud Endpoints with a Google Cloud Functions backend
  version: 1.0.0
host: HOST
schemes:
  - https
produces:
  - application/json
paths:
  /hello:
    get:
      summary: Greet a user
      operationId: hello
      x-google-backend:
        address: https://REGION-FUNCTIONS_PROJECT_ID.cloudfunctions.net/helloGET
      responses:
        '200':
          description: A successful response
          schema:
            type: string

但就我而言,我需要能够代理我的云功能(如反向代理)。


您可以使用端点。当然,您必须手动定义 OpenAPI yaml 文件(版本 2.0,而不是 3!)。使用通配符和路径转换定义

...
paths:
  /account/*:
      get:
        summary: sign-up a user
        operationId: sign-up
        x-google-backend:
          address: https://REGION-FUNCTIONS_PROJECT_ID.cloudfunctions.net
          path_translation: APPEND_PATH_TO_ADDRESS
       responses:
          '200':
            description: A successful response
            schema:
              type: string

The APPEND_PATH_TO_ADDRESS只需将路径值粘贴到后端定义的末尾即可。顺便说一下,仅通过这个定义,您就可以访问所有私有函数端点和子端点,就像您的 swagger 文档一样。

您可以使用 API KEY 保护您的网关(我写了一篇关于这个的文章 https://medium.com/google-cloud/secure-cloud-run-cloud-functions-and-app-engine-with-api-key-73c57bededd1)但文档中还有另一种安全解决方案。

但是,您无法使用 Endpoint 提出的开发人员门户,因为它基于 Endpoint yaml 文件定义,并且不会聚合所有发现的服务定义(在您的/docs path).

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 Google Cloud Functions 实现微服务的 API 网关 的相关文章

随机推荐