zoukankan      html  css  js  c++  java
  • 关于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());
    

      

  • 相关阅读:
    xcode6新建pch文件过程
    系统提供的dispatch方法
    iOS 默认Cell选中
    sqoop部署
    maven自动化部署插件sshexec-maven-plugin
    spring-7、Spring 事务实现方式
    Spring-6.1、Java三种代理模式:静态代理、动态代理和cglib代理
    spring-6、动态代理(cglib 与 JDK)
    spring -3、spring 的 IOC与AOP
    Spring-2、Spring Bean 的生命周期
  • 原文地址:https://www.cnblogs.com/wangzun/p/13397739.html
Copyright © 2011-2022 走看看