Google cloud platform 使用Google云函数API作为服务发现

Google cloud platform 使用Google云函数API作为服务发现,google-cloud-platform,microservices,google-cloud-functions,Google Cloud Platform,Microservices,Google Cloud Functions,我们正在开发一个基于微服务的架构,使用谷歌云功能 我们已经开发了一些功能,并希望实现一个发现服务。此发现服务将用于确定特定功能是否存在并可运行 服务发现本身就是一种云功能。它向下面的API发出rest请求,并使用functions emulator和默认应用程序凭据在本地开发中成功 谷歌为此提供了一个API[ 部署到生产环境时,我们将收到: {“代码”:401,“消息”:“请求缺少所需的身份验证凭据。应为OAuth 2访问令牌、登录cookie或其他有效身份验证凭据。请参阅。”,“状态”:“未经

我们正在开发一个基于微服务的架构,使用谷歌云功能

我们已经开发了一些功能,并希望实现一个发现服务。此发现服务将用于确定特定功能是否存在并可运行

服务发现本身就是一种云功能。它向下面的API发出rest请求,并使用functions emulator和默认应用程序凭据在本地开发中成功

谷歌为此提供了一个API[

部署到生产环境时,我们将收到: {“代码”:401,“消息”:“请求缺少所需的身份验证凭据。应为OAuth 2访问令牌、登录cookie或其他有效身份验证凭据。请参阅。”,“状态”:“未经身份验证”}

云函数是无状态的,因此没有使用我可以看到的服务帐户的选项。如何验证云函数以调用函数api来确定函数是否可用

下面是我们如何在本地开发环境中实现这一点的:

var options = {
    method: 'get',
    uri: `https://cloudfunctions.googleapis.com/v1beta2/projects/${config.PROJECT_ID}/locations/${config.LOCATION_ID}/functions/${functionName}`
  }

  console.log (options.uri);
  request(options, function (err, res, body) {
    if (!err && res.status === 200) {
      if(typeof res.body.httpsTrigger.url !== undefined) {
        console.log('found a function');
        return cb(false, res.body.httpsTrigger.url);
      }
      else {
        console.log('no function found, looking for static content');
        return cb(true, `Service doesn't exist, returned ${res.status}`)
      }
    }
    else {
      console.log('no function found, looking for static content'); 
      return cb(true, `Service doesn't exist, returned ${res.status}`);
    }
  });

您提到的API包含方法:projects.locations.functions.get,它需要以下OAuth作用域之一:

https://www.googleapis.com/auth/cloudfunctions

https://www.googleapis.com/auth/cloud-platform

你可以看一下在线文档。

所以我终于想出了如何做到这一点。这有点像黑客:

  • 下载服务帐户的JSON密钥文件
  • 将JSON文件添加到函数源
  • 安装googleauth库NPM模块
  • 修改请求以使用来自google auth库的客户端

    const keys = require('./VirtualAssistantCred.json');
    
    const{auth}=require('google-auth-library'); const client=auth.fromJSON(键); client.scopes=['']; client.authorize().then(函数(){ 常量url=
    https://cloudfunctions.googleapis.com/v1beta2/projects/${config.PROJECT_ID}/locations/${config.LOCATION_ID}/functions/${functionName}
    ; 请求({url},函数(err,res){ 如果(错误){ log(
    错误:${err}
    ); 返回cb(true,
    服务,${functionName}不存在,返回${res}
    ) }否则{ log(
    响应:${JSON.stringify(res.data)}
    ); log(
    在${res.data.httpsTrigger.url}找到服务
    ); 返回cb(false,res.data.httpsTrigger.url); } }); } ))


  • 因此,如果我将上述作用域之一添加到运行该函数的服务帐户中,那么它应该能够调用API?对此感觉非常密集。因此,该云函数正在调用API以查看其他云函数的可用性。无论是使用rest请求还是API库,都需要OAuth2令牌。Service帐户需要一个密钥文件。云功能没有存储,尽管云存储可能是一个选项?