首页 > 解决方案 > 通过 NodeJS 在 Redis v.5.0 中存储数组或对象列表

问题描述

是否无法通过 Redis 5.0 存储对象数组或对象列表?

我只能让它工作 - 如果我首先将数组/列表转换为 JSON 格式,如下所示:

redis.set('persons', JSON.stringify(array_of_persons)
const persons = JSON.parse(await redis.get('persons'));

或者

redis.hset('my_list', 'persons', JSON.stringify(array_of_persons));
const persons = JSON.parse(await redis.hget('my_list', 'persons'));

但是当我需要从集合中添加/更新/删除对象时,在 javascript 中连续对大集合进行字符串化/解析会产生很多开销 - 那么我如何性能优化这段代码 - 如果不能在更多“ Redis v. 5.0 中的“原生”方式?

标签: node.jsredisioredis

解决方案


您可以将它们放在 Redis 中的列表而不是字符串中。尝试:

redis.lpush('persons', ...array_of_persons)

有关 List 命令的完整补充,请查看:https ://redis.io/commands#list


推荐阅读