1 回答
TA贡献1796条经验 获得超4个赞
redis序列化数据有多重方式:
JacksonJsonRedisSerializer
JdkSerializationRedisSerializer
OxmSerializer
public enum StringSerializer implements RedisSerializer<String> {
INSTANCE;
public byte[] serialize(String s) throws SerializationException {
return (null != s ? s.getBytes() : new byte[0]);
}
public String deserialize(byte[] bytes) throws SerializationException {
if (bytes.length > 0) {
return new String(bytes);
} else {
return null;
}
}
}1234567891011121314
public RedisConnectionFactory redisConnectionFactory() {
JedisConnectionFactory cf = new JedisConnectionFactory();
cf.setHostName("172.16.28.214");
cf.setPort(6379);
//cf.setPassword("123456");
cf.afterPropertiesSet();
return cf;
}
@Test
public void test() {
try {
RedisConnectionFactory connectionFactory = redisConnectionFactory();
RedisTemplate<String, Serializable> redis = new RedisTemplate<String, Serializable>();
redis.setConnectionFactory(connectionFactory);
redis.setKeySerializer(StringSerializer.INSTANCE);
// redis.setValueSerializer(new JdkSerializationRedisSerializer());
redis.setValueSerializer(new JacksonJsonRedisSerializer<TestUser>(TestUser.class));
redis.afterPropertiesSet();
ValueOperations<String, Serializable> ops = redis.opsForValue();
TestUser user1 = new TestUser();
user1.setName("lisi");
user1.setId(20L);
// ops.set("lisi", user1);
TestUser user = (TestUser) ops.get("lisi");
System.out.println(user.getName());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
这里前两种测试
1.StringSerializer.java
2.测试类
- 1 回答
- 0 关注
- 1156 浏览
添加回答
举报