【问题标题】:How do I cache a large array in Redis with a time interval in Node如何在 Redis 中以 Node 中的时间间隔缓存大型数组
【发布时间】:2021-06-29 23:37:15
【问题描述】:

我知道如何在请求发生时使用 node 和 redis 以及中间件功能来缓存数据。

但现在我想以一分钟的时间间隔缓存我的智能合约的完整状态。所以我发出异步请求以在 Node.js 的后端获取智能合约数据。对其进行排序,将排序后的数组存储在 Redis 中。然后从我的中间件访问它。所以它总是被存储和更新,客户端永远不必等到智能合约被获取和排序。

我会怎么做。我没有最小的可重现示例,因为我不知道从哪里开始。我不需要整个代码,只需要一个指向正确方向的快速指针。这就是我获取智能合约状态的方式:

async function getMessages(req, res, next) {
  try {
    console.log(`Getting the entire contract state`);
    const contract = zilliqa.contracts.at(tokenContract);
    const allState = await contract.getState();
    var arr = []
    var sorted =
      Object.keys(allState.texts).forEach(function (key) {
        var value = allState.texts[key];

        Object.keys(value).forEach(function (key_two) {
          var value_two = value[key_two];

          Object.keys(value_two).forEach(function (key_three) {
            var value_three = parseInt(value_two[key_three]);
            var zil = value_three / 1000000000000;
            var rank = (parseInt(key_three) / 12000) * zil;
            arr.push({ 'zil': zil, 'text': key_two, 'address': key, 'block' : key_three, 'rank' : rank });
  
          });

        });
      });

    arr.sort(function (a, b) {
      return parseFloat(b.rank) - parseFloat(a.rank);
    }
    );
}

我想在排序后将arr 存储在 Redis 中。在节点中带有计时器的一分钟时间间隔内。这可能吗?

感谢您的宝贵时间

【问题讨论】:

    标签: node.js caching redis timer blockchain


    【解决方案1】:

    对于间隔,您可以使用setInterval()。一个被广泛使用的redis客户端包简称为redis

    如此组合:

    const redis = require("redis");
    const redisClient = redis.createClient(); // no arg = default options
    
    const getMessages = async () => {
        const arr = [
            {'foo': 1},
            {'foo': 2}
        ];
    
        console.log(arr);
        redisClient.set("messages", arr);
    }
    
    setInterval(getMessages, 60 * 1000); // 60 sec * 1000 milisec
    getMessages(); // so that you don't have to wait 60 sec for the first call from `setInterval()`
    

    【讨论】:

      猜你喜欢
      • 2017-08-20
      • 2022-01-11
      • 2014-10-17
      • 1970-01-01
      • 2020-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-21
      相关资源
      最近更新 更多