使用 Redis 中的嵌套对象? [英] Working with nested objects in Redis?

查看:37
本文介绍了使用 Redis 中的嵌套对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个散列,其中嵌套的属性可能会改变.

"key1": {道具1":{subprop1":could_change"}}

如果我收到prop1.subprop1 已更改的信息,我可以对此属性执行原子更新吗?现在node_redisprop1 保存为一个字符串,表示'[object Object]'.如果我 JSON.stringify() obj 那么我需要检索对象,解析为内存中的对象,进行编辑,然后字符串化并保存对象 - 不知道在此期间是否发生了某些变化.

如果我应该以不同的方式处理这些数据,有人可以解释一下吗?我有一个包含可能嵌套属性的对象,除了需要作为整个对象检索之外,我还需要能够更新其中的部分属性.

感谢您的帮助!

解决方案

Lua 脚本或锁模式可以解决您的问题.

EVAL 'local obj = cjson.decode(redis.call("GET", "key1"));obj.prop1.subprop1 = ARGV[1];redis.call("SET", "key1", cjson.encode(obj));'0 "did_change"

如果你愿意,你甚至可以在 Lua 中做一些更高级的东西来编辑任何键的 JSON 子对象.

查看 Redis SETNX 命令文档,了解如何使用锁的示例.

Say I have a hash where a nested property could change.

"key1": {
  "prop1": {
    "subprop1": "could_change"
  }
}

If I get sent the info that prop1.subprop1 has changed can I preform atomic updates on this property? Right now node_redis saves prop1 as a string that says '[object Object]'. If I JSON.stringify() the obj then I would need to retrieve the object, parse to object in memory, make the edit, and then stringify and save the object -- not knowing if something has changed in the mean time.

If I should be working with this data in a different way could someone please explain? I have an object with may nested attributes that I need to be able to update parts of, in addition to needing to retrieve as a whole object.

Thanks for any help!

解决方案

Lua scripting or a lock pattern would solve your problem.

EVAL 'local obj = cjson.decode(redis.call("GET", "key1")); obj.prop1.subprop1 = ARGV[1]; redis.call("SET", "key1", cjson.encode(obj));' 0 "did_change"

You could even make something more advanced in Lua for editing any key's JSON subobjects if you wanted to.

Look at the Redis SETNX command docs for an example of how to use a lock.

这篇关于使用 Redis 中的嵌套对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆