在AWS lambda中使用node-cache模块不缓存数据

vqlkdk9b  于 2023-06-29  发布在  Node.js
关注(0)|答案(2)|浏览(117)

使用AWS lambda。我们尝试使用node-cache模块来从另一个API获取数据。即使数据正在被设置。当下一个请求到来时,node-cache无法缓存该数据。
下面是我示例代码

//not the original code 

let ClassService = require("./NodeCacheTest");
exports.handler = async (event) => {

     let classService = new ClassService();
     classService.getKey("myKey", (err, value)=> {

         console.log(value);
     });
};

//NodeCacheTest
const NodeCache = require( "node-cache" );
const myCache = new NodeCache();
let CACHEDATA = {
   testing: true,
   time_to_live: 10
};

class NodeCacheTest {

    constructor () {

      let obj = { my: "Special", variable: 42 };
      myCache.get( "myKey", function( err, value ){

           if( err || value == undefined) {

              console.log("No value available!!!");
              myCache.set( "myKey", obj, 10000 );
              console.log("value got cached!!!");

            }
      });

    }

    getKey(key, cb) {

       let obj = { my: "Special", variable: 42 };
       myCache.get( "myKey", function( err, value ){

        if( err || value == undefined) {

           console.log("No value available!!!");
           myCache.set( "myKey", obj, 10000 );
           console.log("value got cached!!!");
           return cb(null,obj);
         } else {

           return cb(null, value);
         }
      });
    }
}
module.exports = NodeCacheTest;

每次我使用Jmeter击中aws lambda端点时...我看到每个调用No value available!!!都被打印出来。但是当我使用一些全局变量(如CACHEDATA)来实现相同的场景时,值被缓存。谁能解释一下我在这方面的行为。

qcuzuvrc

qcuzuvrc1#

由于Lambda的工作方式,您无法在Lambda中使用节点缓存。
Lambda使用的存储不是持久性的。Lambda在容器中运行。有时候你可能会得到容器重用,缓存的数据仍然可用,但这是非常不可靠的。
如果你正在缓存数据,你应该看看其他服务,比如Elasticache,或者你甚至可以按需使用DynamoDB。

v09wglhw

v09wglhw2#

以下是我的答案,也是来自我写的here的评论:
只要lambda的当前执行上下文是有效的,lambda缓存将是完整的。当AWS Lambda执行一个函数时,它会创建一个“执行上下文”,这是一个临时的运行时环境,外部依赖项在其中初始化。当函数是温函数时,并且如果后续请求足够接近,则执行上下文被重用,并且因此存储器中缓存的数据可用。一旦函数变冷,执行上下文就被销毁(沿着其内存中的缓存)。因此,如果您的执行相隔较远,内存缓存将无法工作,因为前一个执行上下文将被销毁。
一个更简单的方法是,当函数是“warm”时,缓存将工作。当它变“冷”时该高速缓存被销毁。
如果你有一个每分钟收到大量请求的lambda,这将工作得很好(缓存应该总是做的)。
这里需要注意的是并发性,每个并发执行都有自己的执行上下文。这意味着如果你有5个lambda表达式同时运行,每个lambda表达式都有自己的执行上下文和自己的缓存,这些缓存不与其他lambda表达式共享。

示例

如果你想给予一下,你可以尝试像

import { LRUCache } from 'lru-cache'

const options = {
  max: 500,

  // for use with tracking overall storage size
  maxSize: 5000,
  sizeCalculation: (value: string, key: string) => {
    // Initial size is zero
    let size = 0

    // Sum up the lengths of each component
    size += new TextEncoder().encode(value).length
    size += new TextEncoder().encode(key).length

    return size
  },

  // how long to live in ms
  ttl: 1000 * 60 * 13,

  // return stale items before removing from cache?
  allowStale: false,

  updateAgeOnGet: false,
  updateAgeOnHas: false
}
const cache = new LRUCache(options)

const userID = '1234'
const time = Date.now()
cache.set(userID, 'value')
cache.get(userID) // "value"

if (cache.get(userID)) {
  const cachedTime = cache.get(userID)
  if (Date.now() - cachedTime > 1000 * 60 * 13) {

    // update record
    
    // update cache
    cache.set(userID, Date.now())

 
  }
}

相关问题