首页 > 解决方案 > 将配置文件从 Google Cloud Storage 提取到 App Engine Standard 的选项有哪些?

问题描述

我需要在我的 App Engine(标准)实例内的 Google Cloud Storage 中的存储桶中读取 .php 文件。

我有两个网络应用程序:

我们还有一些其他的 Web 应用程序也依赖于这些配置文件,但由于它们与这个特定问题无关,我不会解释它们。

我们目前解决这个问题的方法是每分钟在 Web App 2 上运行一个 cron,rsync 从 Google Cloud Storage 到服务器。

我想出了一些选择:

标签: phpgoogle-app-enginegoogle-cloud-platformgoogle-cloud-storage

解决方案


每当您的 Cloud Storage 有更新时,从 App 2 访问您的 Cloud Storage 的一种方法是:

  1. 在您的应用程序上创建一个端点,该端点将启动文件的读取过程。由于您将使用 PHP,因此请使用PHP Cloud Storage 库

导入库:

composer require google/cloud-storage

下载 Cloud Storage 对象的通用代码:

use Google\Cloud\Storage\StorageClient;

/**
 * Download an object from Cloud Storage and save it as a local file.
 *
 * @param string $bucketName the name of your Google Cloud bucket.
 * @param string $objectName the name of your Google Cloud object.
 * @param string $destination the local destination to save the encrypted object.
 *
 * @return void
 */
function download_object($bucketName, $objectName, $destination)
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $object = $bucket->object($objectName);
    $object->downloadToFile($destination);
    printf('Downloaded gs://%s/%s to %s' . PHP_EOL,
        $bucketName, $objectName, basename($destination));
}
  1. 创建一个将在后台运行并在 Cloud Storage 上执行更新时激活的Cloud Function(由 Cloud Storage 触发),您可以指定事件是否是由于某些对象正在:创建、删除、存档或更新(元数据更新),但请记住,您必须使用 Go、Nodejs 或 Python 创建脚本。

该脚本将调用 App 2 上的端点:

import requests

def hello_gcs(event, context):
    """Triggered by a change to a Cloud Storage bucket.
    Args:
         event (dict): Event payload.
         context (google.cloud.functions.Context): Metadata for the event.
    """
    file = event
    url = 'https://app2.appspot.com/'
    response = requests.get(url)
    print(f"call made.")
    print(f"Processing file: {file['name']}.")

请记住在 Cloud Console Functions GUI 的“requirements.txt”选项卡上添加“请求”依赖项。

您可以根据需要使这种交互变得简单或复杂,优点是“同步”仅在 Cloud Storage 存储桶发生更改时发生,而不是像您当前使用 Cron 作业那样每分钟都发生。


推荐阅读