java对象序列化和反序列化,redis存入和获取对象
最近使用redis发现直接存储序列化后的对象更方便,现提供java序列化和反序列化的代码
1.序列化代码:
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) { } return null; }
2.反序列化代码:
public static Object unserialize(byte[] bytes) { ByteArrayInputStream bais = null; try { //反序列化 bais = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(bais); return ois.readObject(); } catch (Exception e) { } return null; }
3.向redis中存入序列化后的对象
public static void setObject(Jedis jedis,int index,String key,Object obj) throws Exception { redisFactory.setBytes(jedis,index,key.getBytes(), SerializeUtil.serialize(obj)); }
4.从redis获取对象
public static Object getObject(Jedis jedis,int index,String key) throws Exception { byte[] objSer = redisFactory.getBytes(jedis,index,key.getBytes()); return SerializeUtil.unserialize(objSer); }
只要还没死,就不要把自己当废物