java Redis 在哈希中存储列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29203717/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Redis storing list inside hash
提问by Shabin Hashim
I have to store some machine details in redis. As there are many different machines i am planning to use the below structure
我必须在redis中存储一些机器详细信息。由于有许多不同的机器,我计划使用以下结构
server1 => {name => s1, cpu=>80}
server2 => {name => s2, cpu=>40}
I need to store more than one value against the key CPU. Also i need to maintain only the last 10 values in the list of values against cpu
我需要针对关键 CPU 存储多个值。此外,我只需要维护针对 cpu 的值列表中的最后 10 个值
1) How can i store a list against the key inside the hash?
1)如何根据哈希中的键存储列表?
2) I read about ltrim. But it accepts a key. How can i do a ltrim for key cpu inside server1?
2)我读过关于 ltrim 的文章。但它接受一个密钥。如何对 server1 中的关键 CPU 执行 ltrim?
I am using jedis.
我正在使用绝地武士。
回答by Itamar Haber
Redis' data structures cannot be nested inside other data structures, so storing a List inside a Hash is not possible. Instead, use different keys for your servers' CPU values (e.g. server1:cpu
).
Redis 的数据结构不能嵌套在其他数据结构中,因此无法将 List 存储在 Hash 中。相反,对服务器的 CPU 值使用不同的键(例如server1:cpu
)。
回答by Nikita Koksharov
It's possible to do this with Redissonframework. It allows to store a reference to Redis object in another Redis object though special reference objects which handled by Redisson.
使用Redisson框架可以做到这一点。它允许通过 Redisson 处理的特殊引用对象将 Redis 对象的引用存储在另一个 Redis 对象中。
So your task could be solved using List inside Map:
所以你的任务可以使用 Map 中的 List 来解决:
RMap<String, RList<Option>> settings = redisson.getMap("settings");
RList<Option> options1 = redisson.getList("settings_server1_option");
options1.add(new Option("name", "s1"));
options1.add(new Option("cpu", "80"));
settings.put("server1", options1);
RList<Option> options2 = redisson.getList("settings_server2_option");
options2.add(new Option("name", "s2"));
options2.add(new Option("cpu", "40"));
settings.put("server2", options2);
// read it
RList<Option> options2Value = settings.get("server2");
Or using Map inside Map:
或者在 Map 中使用 Map:
RMap<String, RMap<String, String>> settings = redisson.getMap("settings");
RMap<String, String> options1 = redisson.getMap("settings_server1_option");
options1.put("name", "s1");
options1.put("cpu", "80");
settings.put("server1", options1);
RMap<String, String> options2 = redisson.getMap("settings_server2_option");
options2.put("name", "s2");
options2.put("cpu", "40");
settings.put("server2", options1);
// read it
RMap<String, String> options2Value = settings.get("server2");