【问题标题】:Redis: Saving a Javascript Object with ListRedis:使用列表保存 Javascript 对象
【发布时间】:2012-10-06 00:12:05
【问题描述】:

基本上,我试图设置一个具有给定值的对象,但即使它看起来很成功,我也无法让它工作。这是我的 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


    【解决方案1】:

    如果您只想保存整个 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,如果您在 student 中除了要存储的列表之外还有其他数据,则需要将 student 拆分为多个键。基本上,列表必须存储在自己的密钥中。这通常通过将列表名称附加到它所属的对象键的末尾来完成。

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

    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));
    

    【讨论】:

      猜你喜欢
      • 2013-11-13
      • 2013-10-22
      • 1970-01-01
      • 1970-01-01
      • 2013-09-02
      • 2014-03-20
      • 2014-08-14
      • 2011-05-22
      • 1970-01-01
      相关资源
      最近更新 更多