Spring Data Redis(sdr)-----序列化

来源:互联网 发布:马赛克复原软件 编辑:程序博客网 时间:2024/05/16 18:13

之前碰到一个问题,这里mark一下:
当redis存储的为hash时,
stackoverflow上的解答见链接

public boolean set(String key,HashMap<String, String> value) {        boolean result = false;        try {            HashOperations<Serializable, String, String> operations = redisTemplate.opsForHash();            operations.putAll(key, value);            result = true;        } catch (Exception e) {            e.printStackTrace();        }        return result;    }

这里注意一下,redis里保存的数据类型最好是String,当然你在代码里可以转换成Integer或者Long或者别的去做操作,只是最后往redis存贮时转换成String就行了。存和取根据需求做转换。

当对hash进行increament操作时,出现:

ERR hash value is not an integer; nested exception is redis.clients.jedis.exceptions.JedisDataException: ERR hash value is not an integer

这里的increament操作代码是

public void incrBy(String key,String field, Long nm) {        BoundHashOperations<Serializable, Object, Object> operations =  redisTemplate.boundHashOps(key);        operations.increment(field, nm);    }

当然代码没错,只是少了对Hash的key和value规定使用org.springframework.data.redis.serializer.StringRedisSerializer的配置。因为当不配置时默认使用jdk的serializer,它就会把hash的key和value(即正常的字符串)序列化后再保存,而StringRedisSerializer保存的是正常的字符串,当然increament也可以递增正常的数字类型字符串(“1”)。

配置如下:

<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">    <property name="connectionFactory" ref="connectionFactory" />    <property name="keySerializer">        <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"></bean>    </property>    <property name="hashKeySerializer">        <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />    </property>    <property name="hashValueSerializer">        <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />    </property> </bean>
阅读全文
0 0