Spring Data RedisTemplate:序列化Value和HashValue [英] Spring Data RedisTemplate: Serializing the Value and HashValue

查看:459
本文介绍了Spring Data RedisTemplate:序列化Value和HashValue的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试按照本教程进行操作: http://javakart.blogspot.in/2012/12/spring-data-redis-hello-world-example.html

I tried following this tutorial: http://javakart.blogspot.in/2012/12/spring-data-redis-hello-world-example.html

我的问题与此有关: 带有弹簧数据Jedis的怪异redis键

My question is related to this: Weird redis key with spring data Jedis

我能够使用StringRedisSerializer来解决键和哈希键.

I was able to solve the keys and hashkeys using the StringRedisSerializer .

<bean 
id="stringRedisSerializer" 
class="org.springframework.data.redis.serializer.StringRedisSerializer"/>

<bean 
id="redisTemplate" 
class="org.springframework.data.redis.core.RedisTemplate"
p:connection-factory-ref="jedisConnectionFactory" 
p:keySerializer-ref="stringRedisSerializer"
p:hashKeySerializer-ref="stringRedisSerializer" 
/>

但是我发现使用序列化器来获取值和哈希值是一个问题.

However I found it a problem using a serializer for the value and hashvalue.

我尝试添加此内容:

p:valueSerializer-ref="stringRedisSerializer"
p:hashValueSerializer-ref="stringRedisSerializer"

但是提示错误: 无法将用户强制转换为java.lang.String"

But an error prompted: "User cannot be cast to java.lang.String"

任何人都可以分享如何使用序列化器作为值/哈希值吗?

Can anyone share how to use a serializer for the value/hashvalue?

推荐答案

Redis将键和值存储为字符串.由您的持久层来处理解析.在示例中,用户是POJO,而不是字符串.我建议您使用JacksonJsonRedisSerializer而不是StringRedisSerializer.这样,您将json存储为您的值.

Redis stores keys and values as string. It's up to your persistence layer to handle the parsing. In the example, User is a POJO and not a String. I suggest that you use JacksonJsonRedisSerializer instead of StringRedisSerializer. This way you're storing json as your value.

<bean id="userJsonRedisSerializer" 
    class="org.springframework.data.redis.serializer.JacksonJsonRedisSerializer">
    <constructor-arg type="java.lang.Class" value="com.mycompany.redis.domain.User"/>
</bean>

这篇关于Spring Data RedisTemplate:序列化Value和HashValue的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆