简体   繁体   English

AWS Lambda /tmp 文件夹不在执行之间共享

[英]AWS Lambda /tmp folder is not shared between executions

I'm trying to temporary cache some data for AWS lambda function executions to omit HTTP request that this lambda does every time right now and optimise its' speed. I'm trying to temporary cache some data for AWS lambda function executions to omit HTTP request that this lambda does every time right now and optimise its' speed.

In "viewer request" I have the following logic (example is pseudo-code) -在“查看器请求”中,我有以下逻辑(示例是伪代码) -

exports.handler = async (event) => {
   // check /tmp folder for data
   const cachedData = await getDataFromCache();

   if (cachedData) {
     return cachedData;
   }

   const data = await getDataFromApi();
   
   // save data for 2 mins in /tmp for re-use in next executions
   await saveDataInCache(data);

   return data;
}

As you can see, I'm trying to save the data in /tmp folder for a few mins in order to re-use it in next executions and reduce the number of API requests.如您所见,我正在尝试将数据保存在/tmp文件夹中几分钟,以便在下次执行时重新使用它并减少 API 请求的数量。

During "viewer request" lambda execution, when I cache data inside /tmp folder, I immediately see that data is available in the logs -在“查看器请求”lambda 执行期间,当我在/tmp文件夹中缓存数据时,我立即看到日志中有数据 -

async function saveDataInCache(data = {}) {
  // save data in tmp folder
  try {
    await fs.outputJson('/tmp/cache.json', {
      data,
      updatedAt: Date.now()
    });
  } catch (err) {
    console.log(`page data save cache error ${err}`);
  }

  // check that data is immediately available
  let fileData = {};
  try {
    fileData = await fs.readJson('/tmp/cache.json');
  } catch (err) {
    console.log(`page data read cache error ${err}`);
  }

  console.log(`check immediate value ${JSON.stringify(fileData)}`);
}

However every time when "viewer request" tries to read the data before saving, it always returns error - ENOENT: no such file or directory, open '/tmp/cache.json' -但是,每次“查看器请求”在保存之前尝试读取数据时,它总是返回错误 - ENOENT: no such file or directory, open '/tmp/cache.json' -

async function getDataFromCache() {
  let fileData = {};

  try {
    fileData = await fs.readJson('/tmp/cache.json');
  } catch (err) {
    console.log(`page data read cache error ${err}`);
  }

  if (isEmpty(fileData)) {
    return undefined;
  }

  const { data = {}, updatedAt = 0 } = fileData;
  const maxCacheTime = updatedAt + DATA_TTL;
  const currentTime = Date.now();
  const isCacheExpired = currentTime > maxCacheTime;

  if (!isCacheExpired) {
    return data;
  }

  return undefined;
}

Does it mean that /tmp folder content is not shared between executions?这是否意味着/tmp文件夹内容不在执行之间共享? Thanks!谢谢!

The /tmp directory is private to each Lambda instance/execution context, it's not shared among all Lambda instances. /tmp目录对每个 Lambda 实例/执行上下文都是私有的,它不在所有 Lambda 实例之间共享。 That means if your request is handled by a different execution context, the data won't be present there.这意味着如果您的请求由不同的执行上下文处理,则数据将不会出现在那里。

Unfortunately you can't really control how these execution contexts are created and deleted, that's something Lambda handles for you in the background.不幸的是,您无法真正控制如何创建和删除这些执行上下文,这是 Lambda 在后台为您处理的。

Short answer is as Maurice said, /tmp is unique to each container, so if you're lucky you'll get the same container back, but it's not guaranteed.正如莫里斯所说,简短的回答是,/tmp 对于每个容器都是独一无二的,所以如果你幸运的话,你会得到相同的容器,但不能保证。 After the container is disposed of all files are gone.容器处理完后,所有文件都消失了。

Use EFS , S3, or Lambda layers if you need real persistent storage between Lambda's.如果您需要 Lambda 之间的真正持久存储,请使用EFS 、S3 或Lambda 层

That being said what's the use case?话虽如此,用例是什么?

Cache.json updated during each execution Cache.json 在每次执行期间更新

Then use EFS/s3(bit slower than EFS) OR a NoSQL database if you're already using one, another collection isn't going to change the world and will be super fast.然后使用 EFS/s3(比 EFS 慢一点)或 NoSQL 数据库(如果您已经在使用),另一个集合不会改变世界,而且速度会非常快。

Static file cache.json Static 文件缓存。json

Either bundle this up with your lambda code or put it in a layer!要么将它与您的 lambda 代码捆绑在一起,要么将其放在一个层中!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM