javascript - Redis:使用列表保存 Javascript 对象

标签 javascript redis

基本上我正在尝试设置一个具有给定值的对象,但我无法让它工作,即使它看起来很成功。这是我的 javascript 对象;

function student(){
  var newStudent = {};
  newStudent.lessons = [1,3,4];

  return newStudent;
}

稍后,当我想要获取学生列表时,我失败了,因为 console.log 打印了 "undefined",但是对象是 not null。我的插入redis的代码;

var student = Students.student();
//Object is not null I checked it
client.set("studentKey1", student, redis.print);
    client.get("studentKey1", function(err, reply){
        console.log(reply.lessons);
    });

两个问题;

首先,请问如何正确操作或者Redis不支持Javascript的列表结构。其次,如果我想使用 studentKey1 获取项目并将项目插入到列表的后面,我该如何实现(我如何使用 RPUSH)?

最佳答案

如果您只想保存整个 Javascript 对象,您需要先将其转换为字符串,因为 Redis 只接受字符串值。

client.set('studentKey1', JSON.stringify(student), redis.print);

将来,如果您的 student 对象具有函数,请记住这些函数不会被序列化并存储在缓存中。从缓存中获取对象后,您需要对其进行再水合。

client.get('studentKey1', function (err, results) {
   if (err) {
       return console.log(err);
   }

   // this is just an example, you would need to create the init function
   // that takes student data and populates a new Student object correctly
   var student = new Student().init(results);
   console.log(student);
}

要使用 RPUSH,如果除了要存储的列表之外,学生中还有其他数据,则需要将学生分成多个键。基本上,列表必须存储在它自己的 key 中。这通常是通过将列表名称附加到它所属的对象键的末尾来完成的。

我使用了multi 操作语法,所以学生被一次性添加到缓存中。请注意,如果 key 尚不存在,将为您创建。

var multi = client.multi().set('studentKey1', 'store any string data');
student.lessons.forEach(function(l) {
    multi.rpush('studentKey1:lessons', l);
});
multi.exec(function (err) { if (err) console.log(err); });

然后要在末尾添加一个新项目,您可以执行如下操作。这会将一个新项目推到列表的末尾。在将新值推到列表末尾之前无需获取该项目。

client.rpush('studentKey1:lessons', JSON.stringify(newItem));

关于javascript - Redis:使用列表保存 Javascript 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12748305/

相关文章:

javascript - backbone.js model.save 没有设置 id

node.js - nodejs 对象 #<Server> 没有方法 'configure'

javascript - 本例中的 Alexa 技能 : How to insert a AMAZON. yesintent 和 AMAZON.nointent ?

javascript - Bootstrap 日期选择器禁用没有当前日期的过去日期

php - Laravel Horizo​​n 中只执行一次作业的设置是什么?

Redis保存错误

redis - 处理 Redis 事件提要中已读/未读消息的最佳方式?

redis - 跨 Redis 分片的排序、并交集

javascript - 如何在按钮单击时调整 div 的大小(如果是百分比 Javascript)

php - 多个交替行颜色