Skip to main content
 首页 » 编程设计

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

2024年02月04日53mengfanrong

我有一个查询,它返回 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()