问题描述:
在Spring中集成了Redis,并使用RedisTemplate.opsForValue().set()设置已经序列化的HashMap对象时报cannot be cast to java.lang.String错误(at org.springframework.data.redis.serializer.StringRedisSerializer.serialize(StringRedisSerializer.java:32))。
解决方案:
在redis的xml配置文件中添加以下信息解决无法序列化问题(主要是设置一系列*Serializer的property):
<bean id="redisTemplate"
class="org.springframework.data.redis.core.StringRedisTemplate">
<property name="connectionFactory" ref="connectionFactory" />
<!-- 如果不配置Serializer,那么存储的时候只能使用String,如果用对象类型存储,那么会提示错误 can't cast to String!!!-->
<property name="keySerializer">
<!--对key的默认序列化器。默认值是StringSerializer-->
<bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
</property>
<!--是对value的默认序列化器,默认值是取自DefaultSerializer的JdkSerializationRedisSerializer。-->
<property name="valueSerializer">
<bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/>
</property>
<!--存储Map时key需要的序列化配置-->
<property name="hashKeySerializer">
<bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
</property>
<!--存储Map时value需要的序列化配置-->
<property name="hashValueSerializer">
<bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/>
</property>
</bean>