現在需要在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());