昨天遇到一个在使用redis放对象时报错的问题,最后发现是实体对象没有实例化序列的原因导致的
对象是之前别人创建的,养成创建对象后就实现序列化是很好的习惯。。。
redis接口:
public interface RedisUtil {
public String setValue(String key ,Object obj);
redis实现:
public class RedisUtilImpl implements RedisUtil {
@Resource
private JedisPool jedisPool;
@Override
public String setValue(String key, Object obj) {
String retv = null;
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
retv = jedis.set(key.getBytes(), SerializableUtil.serialize(obj));
} catch (Exception e) {
e.printStackTrace();
}finally{
jedis.close();
}
return retv;
}
SerializableUtil序列化工具类:
public class SerializableUtil {
public static byte[] serialize(Object object) {
ObjectOutputStream oos = null;
ByteArrayOutputStream baos = null;
try {
// 序列化
baos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(baos);
oos.writeObject(object);
byte[] bytes = baos.toByteArray();
return bytes;
} catch (Exception e) {
e.printStackTrace();
}finally{
IOUtils.closeQuietly(oos);
IOUtils.closeQuietly(baos);
}
return null;
}
正确操作:
public class xxxx implements Serializable{
private static final long serialVersionUID = -995433879447411652L;