关于RedisTemplate的map存储踩坑记录

现在需要在Redis中存储一个map,使用RedisTemplate 建立链接后,执行以下代码:

//cacheKey  缓存key
Map<String,String> map = new HashMap<String,String>();
map.put("a","1");
map.put("b","2");
map.put("c","3");
template.boundHashOps(cacheKey).putAll(map);

  发现Redis存储数据成功。

    现在想要修改map中的数据,当前需要批量修改 将 key = a/b 的数据value修改为3;

还是使用上面的逻辑,执行成功,数据变更。

现在想要把key=a的数据删除,写了如下代码:

Map<String,String> map = new HashMap<String,String>();
map.put("b","2");
map.put("c","3");
template.boundHashOps(cacheKey).putAll(map);

  发现Redis中当前cacheKey对应的数据还是3条记录,后面查看源码:

 public void putAll(K key, Map<? extends HK, ? extends HV> m) {
        if (!m.isEmpty()) {
            byte[] rawKey = this.rawKey(key);
            Map<byte[], byte[]> hashes = new LinkedHashMap(m.size());
            Iterator var5 = m.entrySet().iterator();

            while(var5.hasNext()) {
                Entry<? extends HK, ? extends HV> entry = (Entry)var5.next();
                hashes.put(this.rawHashKey(entry.getKey()), this.rawHashValue(entry.getValue()));
            }

            this.execute((connection) -> {
                connection.hMSet(rawKey, hashes);
                return null;
            }, true);
        }
    }

putAll方法只对传入的map对应key做了处理,并不是对整个缓存的key做覆盖,只能做追加和修改。

所以需要使用hdel删除对应key:

template.boundHashOps(cacheKey).delete(needRemoveKeys.toArray());

  

原文地址:https://www.cnblogs.com/wangzun/p/13397739.html