zoukankan      html  css  js  c++  java
  • spring-data-redis 使用过程中需要注意的地方

    1.序列化问题

         <!--  SDR默认采用的序列化策略有两种,一种是String的序列化策略,一种是JDK的序列化策略。
            StringRedisTemplate默认采用的是String的序列化策略,保存的key和value都是采用此策略序列化保存的。
            RedisTemplate默认采用的是JDK的序列化策略,保存的key和value都是采用此策略序列化保存的。
            就是因为序列化策略的不同,即使是同一个key用不同的Template去序列化,结果是不同的。所以根据key去删除数据的时候就出现了删除失败的问题。 
         -->
        <!-- redis 序列化策略 ,通常情况下key值采用String序列化策略, -->
        <!-- 如果不指定序列化策略,StringRedisTemplate的key和value都将采用String序列化策略; -->
        <!-- 但是RedisTemplate的key和value都将采用JDK序列化 这样就会出现采用不同template保存的数据不能用同一个template删除的问题 -->
        <bean id="stringRedisSerializer"  class="org.springframework.data.redis.serializer.StringRedisSerializer" />
        <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
            <property name="connectionFactory" ref="connectionFactory" /> 
            <property name="keySerializer" ref="stringRedisSerializer" />
            <property name="hashKeySerializer" ref="stringRedisSerializer" />
            <property name="valueSerializer" ref="stringRedisSerializer"/>
        </bean>

    2. 设置一个键值及其过期时间

    错误的设置方式:

        /**
         * Overwrite parts of {@code key} starting at the specified {@code offset} with given {@code value}.
         *
         * @param key must not be {@literal null}.
         * @param value
         * @param offset
         * @see <a href="http://redis.io/commands/setrange">Redis Documentation: SETRANGE</a>
         */
        void set(K key, V value, long offset);

    正确的设置方式:

        /**
         * Set the {@code value} and expiration {@code timeout} for {@code key}.
         *
         * @param key must not be {@literal null}.
         * @param value
         * @param timeout
         * @param unit must not be {@literal null}.
         * @see <a href="http://redis.io/commands/setex">Redis Documentation: SETEX</a>
         */
        void set(K key, V value, long timeout, TimeUnit unit);

    3.模糊删除

    错误的方式:

            Set<String> keys=redisTemplate.keys(prex+"*");
    
            /*for test    
             *Iterator<String> it=keys.iterator();
             * while(it.hasNext()){
                redisTemplate.delete((String)it.next());
            }*/

    正确的方式:

     Set<String> keys=redisTemplate.keys(prex+"*");
     redisTemplate.delete(keys);

    参考文献:

    【1】http://www.cnblogs.com/shihaiming/p/6019795.html

    【2】

  • 相关阅读:
    打印机共享为什么老是出现“操作无法完成(错误 0X00000709)。再次检查打印机名称、并确保打印机连接网络
    给UITextField设置头或尾空白
    Objective-C中的关联(objc_setAssociatedObject,objc_getAssociatedObject,objc_removeAssociatedObjects)
    定时器在多线程中的使用
    block知识点
    UIViewController新方法的使用(transitionFromViewController:toViewController:duration:options:animations:completion:)
    NSMutableAttributedString 的使用方法,设置格式
    statusbar的颜色设置
    获取图片的缩略图
    彻底理解position与anchorPoint
  • 原文地址:https://www.cnblogs.com/davidwang456/p/6756082.html
Copyright © 2011-2022 走看看