【问题标题】:Can I create signed URLs for multiple objects at once in Google Cloud Storage?我可以在 Google Cloud Storage 中一次为多个对象创建签名 URL 吗?
【发布时间】:2019-12-13 13:29:18
【问题描述】:

我在 Google Cloud Storage 存储桶下的Picture(类似文件夹)内上传了多张图片。

例如。 Picture/a.jpg, Picture/b.jpg, Pictuer/c.jpg, .....

现在,我想将 Cloud Storage 中的这些多张图片作为列表直接显示到我的 cakephp 2.x Web 应用程序中。

根据 Google Cloud Storage 文档,要访问存储桶内的每个对象,必须生成 Signed URLs。 因此,我根据从数据库中选择的数据为每个对象创建了签名 URL。以下是我的示例代码。

<?php
# Imports the Google Cloud client library
use Google\Cloud\Storage\StorageClient;
use Google\Cloud\Core\Exception\GoogleException;

function index() {
    //$rsl = 'select data from database';
    for($i=0; $i<$count; $i++) {
        # create url to access image from google cloud storage
        $file_path = $rsl[$i]['pic']['file_path'];
        if(!empty($file_path)) {
            $rsl[$i]['pic']['real_path'] = $this->get_object_v4_signed_url($file_path);
        } else {
            $rsl[$i]['pic']['real_path'] = '';
        }

    }
}

/**
* Generate a v4 signed URL for downloading an object.
*
* @param string $bucketName the name of your Google Cloud bucket.
* @param string $objectName the name of your Google Cloud object.
*
* @return void
*/
function get_object_v4_signed_url($objectName) {
    $cloud = parent::connect_to_google_cloud_storage();
    $storage = $cloud[0];
    $bucketName = $cloud[1];
    $bucket = $storage->bucket($bucketName);
    $object = $bucket->object($objectName);
    if($object->exists()) {
        $url = $object->signedUrl(
        # This URL is valid for 1 minutes
        new \DateTime('1 min'),
            [
                'version' => 'v4'
            ]
        );
    } else {
        $url = '';
    }
    return $url;
}
?>

问题是,生成时间太长,因为每个文件都生成为 v4 签名的 URL。当我阅读 Google Cloud Storage 文档时,我没有看到一次生成多个对象的 v4 签名 URL(可能是我错了)。那么,有没有办法加快这个生成过程呢?

【问题讨论】:

    标签: php google-cloud-storage


    【解决方案1】:

    正如您所提到的,Google Cloud Storage 文档中没有说明如何像您一样使用 PHP 为多个对象生成签名 URL。但是,我发现使用gsutil signurl 命令,可以指定多个路径,甚至可以使用通配符:

    gsutil signurl -d 1m ~/sandbox/key.json gs://bucket_name/object_1.jpg gs://bucket_name/object_2.jpg ...
    
    gsutil signurl -d 1m ~/sandbox/key.json gs://bucket_name/*
    
    

    这是在gsutil help signurl 页面中指定的:“可以提供多个 gs:// url,并且可以包含通配符。将为每个提供的 url 生成一个签名的 url,授权给指定的 HTTP 方法并且对给定的有效持续时间。”

    另一个选项可能是在您的 APP 中使用多线程,here 您将了解如何使用 pthreads API 执行多线程。如果您选择使用此 API,请记住(来自 documentation):

    警告 pthreads 扩展不能在 Web 服务器环境中使用。因此,PHP 中的线程仅限于基于 CLI 的应用程序。

    警告 pthreads (v3) 只能用于 PHP 7.2+:这是由于 ZTS 模式在 7.0 和 7.1 中不安全。

    但是由于您有一个网络应用程序,我认为这些解决方案都对您没有用处。除此之外,您还可以尝试使用Cloud Functions 来生成签名的 URL。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-01-12
      • 2013-01-12
      • 1970-01-01
      • 2020-10-07
      • 2015-08-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多