php - 从 Google Cloud 请求图像使页面速度极慢

标签 php google-app-engine google-cloud-storage

我正在制作一个 PHP Google App Engine 网站,我发现从 Google Cloud 服务请求图像会使页面加载速度极其缓慢。

如果不加载图像,页面加载大约需要 0.5 秒,而加载图像则需要 10-15 秒。我认为我做错了什么,因此我们将不胜感激任何帮助。

See this example .

我的代码

require_once "google/appengine/api/cloud_storage/CloudStorageTools.php";
use google\appengine\api\cloud_storage\CloudStorageTools;

...

function cloudStorageUrl($url, $size, $crop) {
    if (file_exists($url)) {
        $object_image_url = CloudStorageTools::getImageServingUrl($object_image_file, ['size' => $size, 'crop' => $crop]);
        return $object_image_url;
    }
    else {
        return false;
    }
}

最佳答案

按照 Paul 和 Stuart 的建议,我通过在 Google Cloud SQL 中创建一个表来解决这个问题,我可以在其中存储从 Google Cloud Storage 返回的 url,这样我就不必重复请求该 url。

代码示例

// Cloud Storage URL function
function cloudStorageUrl($url, $size, $crop) {
    if (file_exists($url)) {
        $object_image_url = CloudStorageTools::getImageServingUrl($object_image_file, ['size' => $size, 'crop' => $crop]);
        return $object_image_url;
    } else {
        return 'none';
    }
}

// Connect to database
$db = new pdo('mysql:unix_socket=/cloudsql/<your-project-id>:<your-instance-name>;dbname=guestbook', 'root', '');

foreach($db->query('SELECT * FROM `images` WHERE `id`="'.$id.'"') as $row) {
    // Check if Cloud Storage URL already exists
    if ($row['url'] && $row['url'] !== 'none') {
        $url = $row['url'];
    } else {
        // Get the Cloud Storage URL and save it
        $url = cloudStorageUrl($row['cloud_storage_location'], 400, false);
        $stmt = $db->prepare('INSERT INTO `images` (id, url) VALUES (:id, :url ON DUPLICATE KEY UPDATE url=VALUES(url))');
        $stmt->execute(array(':id' => intval($id), ':url' => htmlspecialchars($url)));
    }
}

关于php - 从 Google Cloud 请求图像使页面速度极慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27058187/

相关文章:

javascript - 是否可以在 javascript/jquery 函数中使用 jinja 值

json - BigQuery 加载 JSON 错误 "Could not convert value to string"

sql - 如何生成大型 BigQuery 表的排序导出?

google-app-engine - App Engine 实例的 GCS 入口和导出费用

php - 无法从 PHP 访问数据库值

php - 使用 postgres 数据库表为表创建删除按钮

php - 每小时自动运行一个 php

php - 在从数据库获取设置的函数上我遇到了错误

java - Google App Engine 查询过滤器按日期

java - 通过邮件发送非英文文本的问题