【问题标题】:I wanna store multiple map values in single key of Redis in my Java Code我想在我的 Java 代码中将多个映射值存储在 Redis 的单个键中
【发布时间】:2018-08-08 14:48:54
【问题描述】:

在下面,我有一个 HashMap 列表,我想将所有这些映射存储在 redis 的单个键中,但我没有任何方法可以将所有这些映射存储在单个键中。请帮我解决这个问题。

Jedis jedis = new Jedis("localhost");
List <HashMap<String, String>> listOfMaps = new ArrayList<HashMap<String, String>>();
listOfMaps.add(new HashMap<String,String>);
listOfMaps.add(new HashMap<String,String>);
listOfMaps.add(new HashMap<String,String>);
listOfMaps.add(new HashMap<String,String>);
.
.
.
and so on lets take upto 10 values

现在,我想将这些地图存储在这样的键中:

for(int i=0;i<listOfMaps.size();i++){
   jedis.hmset("mykey",listofMaps[i]);
}

但在他的情况下,hmset 会覆盖所有旧值以写入新值。 请告诉我将所有这些地图值存储在单个键 mykey 中的任何替代方法。

【问题讨论】:

  • 首先使用 hmget - 现在将 listOfMaps 中的新条目添加到其中 - 然后使用 hmset 将其放回
  • 我已经尝试过了,但是当我使用 hmset 时,它再次替换了以前的 map 值。我的主要动机是将所有这些映射值存储在一个键中。
  • hmset 表示 redis 中的单个哈希表。您想如何在 redis 的单个哈希图中表示多个哈希表?由于您所有的哈希表看起来都像 为什么不将它们作为不同的属性值添加到同一个键。 ?

标签: java dictionary redis


【解决方案1】:

您可以使用Redisson 框架提供的Multimap 对象。它允许将每个映射键的多个值存储为列表或集合。示例如下:

RMultimap<String, Integer> multimap = redisson.getListMultimap("myMultimap");
for (int i = 0; i < 10; i++) {
    myMultimap.put("someKey", i);
}
// returns Redis list object
RList list = myMultimap.get("someKey");

【讨论】:

    【解决方案2】:

    你可以使用类似下面的东西

     public static void main(String[] args) {
    
        Map<String, List<String>> map = new HashMap<String, List<String>>();
    
        List<String> valSetOne = new ArrayList<String>();
        valSetOne.add("ABC");
        valSetOne.add("BCD");
        valSetOne.add("DEF");
    
        List<String> valSetTwo = new ArrayList<String>();
        valSetTwo.add("CBA");
        valSetTwo.add("DCB");
    
        map.put("FirstKey", valSetOne);
        map.put("SecondKey", valSetTwo);
    
        for (Map.Entry<String, List<String>> entry : map.entrySet()) {
    
            String key = entry.getKey();
    
            List<String> values = entry.getValue();
    
            System.out.println("Value of " + key + " is " + values);
    
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-09
      • 2017-11-03
      • 1970-01-01
      • 2020-02-18
      • 2021-01-01
      • 2013-07-17
      • 2014-07-22
      • 1970-01-01
      相关资源
      最近更新 更多