7.2. 多值映射(Multimap)

基于Redis的Redisson的分布式RMultimap Java对象允许Map中的一个字段值包含多个元素。字段总数受Redis限制,每个Multimap最多允许有4 294 967 295个不同字段。

7.2.1. 基于集(Set)的多值映射(Multimap)

基于Set的Multimap不允许一个字段值包含有重复的元素。

  1. RSetMultimap<SimpleKey, SimpleValue> map = redisson.getSetMultimap("myMultimap");
  2. map.put(new SimpleKey("0"), new SimpleValue("1"));
  3. map.put(new SimpleKey("0"), new SimpleValue("2"));
  4. map.put(new SimpleKey("3"), new SimpleValue("4"));
  5. Set<SimpleValue> allValues = map.get(new SimpleKey("0"));
  6. List<SimpleValue> newValues = Arrays.asList(new SimpleValue("7"), new SimpleValue("6"), new SimpleValue("5"));
  7. Set<SimpleValue> oldValues = map.replaceValues(new SimpleKey("0"), newValues);
  8. Set<SimpleValue> removedValues = map.removeAll(new SimpleKey("0"));

7.2.2. 基于列表(List)的多值映射(Multimap)

基于List的Multimap在保持插入顺序的同时允许一个字段下包含重复的元素。

  1. RListMultimap<SimpleKey, SimpleValue> map = redisson.getListMultimap("test1");
  2. map.put(new SimpleKey("0"), new SimpleValue("1"));
  3. map.put(new SimpleKey("0"), new SimpleValue("2"));
  4. map.put(new SimpleKey("0"), new SimpleValue("1"));
  5. map.put(new SimpleKey("3"), new SimpleValue("4"));
  6. List<SimpleValue> allValues = map.get(new SimpleKey("0"));
  7. Collection<SimpleValue> newValues = Arrays.asList(new SimpleValue("7"), new SimpleValue("6"), new SimpleValue("5"));
  8. List<SimpleValue> oldValues = map.replaceValues(new SimpleKey("0"), newValues);
  9. List<SimpleValue> removedValues = map.removeAll(new SimpleKey("0"));

7.2.3. 多值映射(Multimap)淘汰机制(Eviction)

Multimap对象的淘汰机制是通过不同的接口来实现的。它们是RSetMultimapCache接口和RListMultimapCache接口,分别对应的是Set和List的Multimaps。

所有过期元素都是通过org.redisson.EvictionScheduler实例来实现定期清理的。为了保证资源的有效利用,每次运行最多清理100个过期元素。任务的启动时间将根据上次实际清理数量自动调整,间隔时间趋于1秒到2小时之间。比如该次清理时删除了100条元素,那么下次执行清理的时间将在1秒以后(最小间隔时间)。一旦该次清理数量少于上次清理数量,时间间隔将增加1.5倍。

RSetMultimapCache的使用范例:

  1. RSetMultimapCache<String, String> multimap = redisson.getSetMultimapCache("myMultimap");
  2. multimap.put("1", "a");
  3. multimap.put("1", "b");
  4. multimap.put("1", "c");
  5. multimap.put("2", "e");
  6. multimap.put("2", "f");
  7. multimap.expireKey("2", 10, TimeUnit.MINUTES);