我可以在Google Cloud Storage中一次为多个对象创建签名的URL吗?

时间:2019-08-06 03:23:03

标签: php google-cloud-storage

我正在Picture(如文件夹)内的Google Cloud Storage存储桶中上传多张图像。

例如。 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(可能是我错了)。那么,有什么办法可以加快生成过程的速度吗?

1 个答案:

答案 0 :(得分:0)

正如您所提到的,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://网址,其中可能包含通配符。将为每个提供的网址生成一个已签名的网址,该网址授权用于指定的HTTP方法,并且对于给定的持续时间。”

另一种选择是在您的APP中使用多线程,here您将找到如何使用pthreads API执行多线程。如果您选择使用此API,则应牢记(来自documentation):

  

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

     

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

但是,由于您具有Web APP,因此我认为这些解决方案都不会对您有用。除此之外,您可以尝试使用Cloud Functions来生成签名的URL。

相关问题