node.js - 我应该如何在redis中存储数组?

标签 node.js npm redis

我有一个查询,它返回 javaScript (json) 中的对象数组,我需要将其保存在 redis 中,而不需要 foreach,

我目前使用 redis set 命令并将 json 数组转换为 string,但我不'不知道这有多优化,因为我们正在讨论将 json 数组转换为 string

这是您用来尝试模拟 redisjson 对象的数组存储的代码。

client.set('proyectos',JSON.stringify(proyectos));
 res.json(proyectos);

在这里,我提取了链并将其转换回 json 对象数组。

redisCtrl.getProyectos=async (req,res,next)=>{
   client.get('proyectos').then(proyectos=>{ 
       if(proyectos){
          console.log("ok"); 
          res.json(JSON.parse(proyectos)); 
        }
        else
          next();
   }).catch(err=>{
       console.error("error"); 
       next();
   });
};  

这将返回以下内容:

[{"id":1,"nombre":"cualquier","descripcion":"具体描述","monto":"100000","fecha":"2019-10-16 ","estado":true},{"id":2,"nombre":"conjunto autosustentable","descripcion":"es un proyecto creado para有利于媒体环境和减少成本的estilo de vida","monto ":"15000","fecha":"2019-12-16","estado":true},{"id":3,"nombre":"cultivo autosustentable","descripcion":"el objetivo es reducir食品生产成本和环境偏好","monto":"190000000","fecha":"2019-12-16","estado":true}]

这本身并不是一个错误,但我认为这是一种不好的做法,尤其是对于大规模生产环境来说,那么我应该如何以最优化的方式做到这一点?

最佳答案

如果你的对象很浅,你可以对每个项目使用散列,对数组使用列表

使用列表键作为项目键的名称itemlist 使用哈希在键中存储实际数据,例如 item:1

const data = [
    {
        id: 1,
        nombre: 'cualquier',
        descripcion: 'descripción muy especifica',
        monto: '100000',
        fecha: '2019-10-16',
        estado: true
    },
    {
        id: 2,
        nombre: 'conjunto autosustentable',
        descripcion:
            'es un proyecto creado para favorecer al medio ambiente y reducir costos de estilo de vida',
        monto: '15000',
        fecha: '2019-12-16',
        estado: true
    },
    {
        id: 3,
        nombre: 'cultivo autosustentable',
        descripcion:
            'el objetivo es reducir el costo de producción de alimento y favorecer el medio ambiente',
        monto: '190000000',
        fecha: '2019-12-16',
        estado: true
    }
]

// using ioredis lib in this example
// saving it to redis

for (let i = 0; i < data.length; i++) {
    const item = data[i]
    await redis.hmset('item:${item.id}', item)
    await redis.lpush('itemlist', `item:${item.id}`)
}

// getting it back from redis: first geet the keys ; then get all the data
const keys = await redis.lrange('itemlist', 0, -1) // 0, -1 => all items

const p = redis.pipeline()
for (let i = 0; i < keys.length; i++) {
    const key = keys[i];
    p.hgetall(key)
}
const resp = await p.exec()

关于node.js - 我应该如何在redis中存储数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58469803/

相关文章:

javascript - 在 sails js 中处理事件

reactjs - 错误: Do not use Array index in keys

javascript - Socket.io 使用参数创建空间

amazon-web-services - 在 Elasticache (Redis) 中分区数据的正确方法

node.js - 所有 mocha 测试都在本地通过,但在 Travis CI 上失败

node.js - NodeJS 水平缩放

node.js - Mongoose - 如何查询多个模型的 id?

javascript - 无法在 puppeteer Node js 中启动 chrome

android - 无法在 Windows 10 上为 Cordova 设置 ANDROID_HOME

c# - 自安装内存缓存 - 它存在吗?