我正在制作一个 PHP Google App Engine 网站,我发现从 Google Cloud 服务请求图像会使页面加载速度极其缓慢。
如果不加载图像,页面加载大约需要 0.5 秒,而加载图像则需要 10-15 秒。我认为我做错了什么,因此我们将不胜感激任何帮助。
我的代码
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/