php - 将配置文件从 Google Cloud Storage 提取到 App Engine Standard 的选项有哪些?
问题描述
我需要在我的 App Engine(标准)实例内的 Google Cloud Storage 中的存储桶中读取 .php 文件。
我有两个网络应用程序:
- Web App 1 是一个内部工具(托管在本地),它允许我们更改一些配置并将其以 JSON 形式保存到本地 .php 文件,然后再同步到 Google Cloud Storage。
- Web App 2 是另一个托管在 App Engine 上的内部工具(标准 - php72)。这个应用程序需要不断地从 Web App 1 中读取配置文件。
我们还有一些其他的 Web 应用程序也依赖于这些配置文件,但由于它们与这个特定问题无关,我不会解释它们。
我们目前解决这个问题的方法是每分钟在 Web App 2 上运行一个 cron,rsync 从 Google Cloud Storage 到服务器。
我想出了一些选择:
- 将存储桶中的配置文件流式传输到 Web App 2
- Cloud Storage Fuse,但我必须想办法重新加载 PHP
- 切换到 App Engine (Flex),创建一个已安装 gcloud 和存储桶凭据的自定义 docker 映像。这个选项的问题是我们的生产环境与我们的暂存环境不同
解决方案
每当您的 Cloud Storage 有更新时,从 App 2 访问您的 Cloud Storage 的一种方法是:
- 在您的应用程序上创建一个端点,该端点将启动文件的读取过程。由于您将使用 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));
}
- 创建一个将在后台运行并在 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 作业那样每分钟都发生。
推荐阅读
- shell - 这个 shell 重定向命令中的“200”是什么?文件描述符?
- python - 在numpy中进入两个不同维度的数组时,点积和乘法矩阵是否相同
- flutter - 将 Flutter Barcode Result 单行转换为列表
- c - 忽略信号的不同方法?
- spring-boot - Spring Boot - 我是否必须使用 Transactional 标记处理和保存数据的方法?
- python - numpy 数组中特定值的新列
- c# - 创建组合框并动态填充项目
- javascript - 尝试实现控制器文件
- python - 什么是包含重音字符的好正则表达式?
- typescript - 创建一个函数类型,该函数类型返回带有可能额外道具的参数对象