先看实例:
...
@Autowired
RedisTemplate redisTemplate;
public void testGetUserByName(){
User user = new User();
user.setUserName("用户1");
redisTemplate.opsForValue().set("user1", user);
Assert.assertEquals(user.getUserName(), ((User) jedisClient.get("user1")).getUserName());
}
//User已经实现了Serializable接口
//配置的是org.springframework.data.redis.serializer.StringRedisSerializer
...
使用StringRedisSerializer
直接缓存Object会出现转换错误:
java.lang.ClassCastException: dev.entity.User cannot be cast to java.lang.String
at org.springframework.data.redis.serializer.StringRedisSerializer.serialize(StringRedisSerializer.java:32)
at org.springframework.data.redis.core.AbstractOperations.rawValue(AbstractOperations.java:112)
at org.springframework.data.redis.core.DefaultValueOperations.set(DefaultValueOperations.java:168)
at dev.dao.RedisTest.testGetUserByName(RedisTest.java:22)
...
解决方法
StringRedisTemplate
相当于RedisTemplate<String, String>
的实现。
缓存时需要把Object类转为byte[]再存到redis中,反之要从redis中获取byte[]再转成Object。
看了很多人的实现方法,感觉这个实现最优雅便捷。最主要的转换代码如下:
/**
* 描述 : <byte[]转Object>. <br>
* <p>
* <使用方法说明>
* </p>
*
* @param bytes
* @return
*/
private Object toObject(byte[] bytes) {
Object obj = null;
try {
ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bis);
obj = ois.readObject();
ois.close();
bis.close();
} catch (IOException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
return obj;
}
private byte[] toByteArray(Object obj) {
byte[] bytes = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(obj);
oos.flush();
bytes = bos.toByteArray();
oos.close();
bos.close();
} catch (IOException ex) {
ex.printStackTrace();
}
return bytes;
}
}
相当于封装了一个处理Object缓存的类,之后用这个类与redis做交流。
package dev.dao;
import dev.cache.JedisClient;
import dev.entity.User;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:/spring/spring-redis.xml")
public class RedisTest {
@Autowired
JedisClient jedisClient;
@Test
public void testGetUserByName(){
User user = new User();
user.setUserName("用户1");
jedisClient.put("user1", user);
Assert.assertEquals(user.getUserName(), ((User) jedisClient.get("user1")).getUserName());
}
}
//测试成功
网友评论