spring-data-redis 使用过程中需要注意的地方
生活随笔
收集整理的這篇文章主要介紹了
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】
?
轉載于:https://www.cnblogs.com/davidwang456/p/6756082.html
總結
以上是生活随笔為你收集整理的spring-data-redis 使用过程中需要注意的地方的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: JMeter使用碰到的问题
- 下一篇: 分布式服务化系统一致性的“最佳实干”--