我正在制作一个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;
}
}
答案 0 :(得分:2)
正如Paul& amp; 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)));
}
}