我使用 lambda@edge 函数动态调整图像大小。这工作得很好 - 除了同时调用这个函数 fe 5x 时。然后在 s3 上查找图像大约需要 4 秒。因为 lambda@edge 函数只有一个最大值。超时 5 秒,我只剩下 1 秒,这对于处理图像来说太少了。
所以我问自己,为什么 5s 的限制这么低?
也许我可以优化图像的 s3-lookup,它在多次调用该函数时需要 4 秒(当只为 1 个图像调用它时,它在 200 毫秒时非常快)。
s3 查找:
export async function s3ObjectExists(Key: string, Bucket = BucketFiles) {
try {
await s3HeadObject(Key, Bucket);
} catch (e) {
if (e && e.code === 'NotFound') {
return false;
}
throw new Error(e);
}
return true;
}
lambda@edge 函数的完整代码(简化):
exports.handler = async (e) => {
const { request, response } = e.Records[0].cf;
const q = getQuery(request.querystring);
const { uri } = request;
const match = uri.match(/^\/((.+)\.(png|jpg|jpeg))/i);
const key = match[1];
const keyWithoutExt = match[2];
const keyExt = match[3] as 'jpg' | 'png';
const ext = q.format === 'webp' ? 'webp' : keyExt.toLowerCase();
const newKey = getKey(`${keyWithoutExt}${JSON.stringify(q)}.${keyExt}`);
if (await s3ObjectExists(newKey, bucketTmp)) {
const file = await s3GetObject(newKey, bucketTmp);
response.body = file.Body.toString('base64');
} else {
const file = await s3GetObject(key, bucket);
let sharpConfig = sharp(file.Body as Buffer);
if (q.width || q.height) {
sharpConfig = sharpConfig.resize(q.width, q.height, {
withoutEnlargement: true
});
}
const buffer = await sharpConfig.toBuffer();
await s3PutObject(bucketTmp, newKey, buffer, {
CacheControl: 'max-age=31536000',
Tagging: 'ImageCache=true'
});
response.body = buffer.toString('base64');
}
response.status = 200;
response.bodyEncoding = 'base64';
response.headers['content-type'] = [
{
key: 'Content-Type',
value: 'image/' + ext === 'jpg' ? 'jpeg' : ext
}
];
return response;
};