【发布时间】:2017-09-20 16:03:07
【问题描述】:
我们应用程序中使用的图像是从 Amazon CloudFront 呈现的。
修改现有映像后,它不会立即反映映像更改,因为 CloudFront 大约需要 24 小时才能更新。
作为一种解决方法,我计划致电CreateInvalidation 以立即反映文件更改。
是否可以在没有 SDK 的情况下使用此失效调用?
使用ColdFusion编程语言,似乎没有SDK。
【问题讨论】:
我们应用程序中使用的图像是从 Amazon CloudFront 呈现的。
修改现有映像后,它不会立即反映映像更改,因为 CloudFront 大约需要 24 小时才能更新。
作为一种解决方法,我计划致电CreateInvalidation 以立即反映文件更改。
是否可以在没有 SDK 的情况下使用此失效调用?
使用ColdFusion编程语言,似乎没有SDK。
【问题讨论】:
您可以简单地发出 POST 请求。 Steve Jenkins 的 PHP 示例
<?php
/**
* Super-simple AWS CloudFront Invalidation Script
* Modified by Steve Jenkins <steve stevejenkins com> to invalidate a single file via URL.
*
* Steps:
* 1. Set your AWS Access Key
* 2. Set your AWS Secret Key
* 3. Set your CloudFront Distribution ID (or pass one via the URL with &dist)
* 4. Put cf-invalidate.php in a web accessible and password protected directory
* 5. Run it via: http://example.com/protected_dir/cf-invalidate.php?filename=FILENAME
* or http://example.com/cf-invalidate.php?filename=FILENAME&dist=DISTRIBUTION_ID
*
* The author disclaims copyright to this source code.
*
* Details on what's happening here are in the CloudFront docs:
* http://docs.amazonwebservices.com/AmazonCloudFront/latest/DeveloperGuide/Invalidation.html
*
*/
$onefile = $_GET['filename']; // You must include ?filename=FILENAME in your URL or this won't work
if (!isset($_GET['dist'])) {
$distribution = 'DISTRIBUTION_ID'; // Your CloudFront Distribution ID, or pass one via &dist=
} else {
$distribution = $_GET['dist'];
}
$access_key = 'AWS_ACCESS_KEY'; // Your AWS Access Key goes here
$secret_key = 'AWS_SECRET_KEY'; // Your AWS Secret Key goes here
$epoch = date('U');
$xml = <<<EOD
<InvalidationBatch>
<Path>{$onefile}</Path>
<CallerReference>{$distribution}{$epoch}</CallerReference>
</InvalidationBatch>
EOD;
/**
* You probably don't need to change anything below here.
*/
$len = strlen($xml);
$date = gmdate('D, d M Y G:i:s T');
$sig = base64_encode(
hash_hmac('sha1', $date, $secret_key, true)
);
$msg = "POST /2010-11-01/distribution/{$distribution}/invalidation HTTP/1.0\r\n";
$msg .= "Host: cloudfront.amazonaws.com\r\n";
$msg .= "Date: {$date}\r\n";
$msg .= "Content-Type: text/xml; charset=UTF-8\r\n";
$msg .= "Authorization: AWS {$access_key}:{$sig}\r\n";
$msg .= "Content-Length: {$len}\r\n\r\n";
$msg .= $xml;
$fp = fsockopen('ssl://cloudfront.amazonaws.com', 443,
$errno, $errstr, 30
);
if (!$fp) {
die("Connection failed: {$errno} {$errstr}\n");
}
fwrite($fp, $msg);
$resp = '';
while(! feof($fp)) {
$resp .= fgets($fp, 1024);
}
fclose($fp);
print '<pre>'.$resp.'</pre>'; // Make the output more readable in your browser
【讨论】:
使对象无效的一些替代方法是:
image_1.jpg改成image_2.jpg
?version=1)识别为文件名的一部分,因此您的应用可以使用 ?version=2 引用新版本,这会强制 CloudFront 将其视为不同的对象【讨论】:
对于频繁修改,我认为最好的方法是在图片url(对象的时间戳或哈希值)后附加一个查询字符串,并配置Cloudfront转发查询字符串,查询字符串时总是返回最新的图片不同。
对于不经常修改的情况,除了 SDK,您还可以使用 AWS CLI,它还允许在构建时使缓存无效,与您的 CI/CD 工具集成。
例如
aws cloudfront create-invalidation --distribution-id S11A16G5KZMEQD \
--paths /index.html /error.html
【讨论】: