redis不支持直接将java对象存储到数据库中,所以需要将java对象进行序列化得到字节数组,然后将字节数组存在redis中,需要数据时候就从redis中取出字节数组,再经过反序列化将自己数组转化成对象使用。
下面的反序列化和序列化工具类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| public class SerializeUtils {
public static byte[] serialize(Object obj) { byte[] bytes = null; try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ; ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(obj); bytes = baos.toByteArray(); baos.close(); oos.close(); } catch (IOException e) { e.printStackTrace(); } return bytes; }
public static Object deSerialize(byte[] bytes){ Object obj=null; try { ByteArrayInputStream bais=new ByteArrayInputStream(bytes); ObjectInputStream ois=new ObjectInputStream(bais); obj=ois.readObject(); } catch (Exception e) { e.printStackTrace(); } return obj; } }
|
下面简单测试:
1 2 3 4 5 6 7 8 9 10
| Jedis jedis=JedisUtil.getJedis();
User user=new User(“1000”, “宝宝”, “xioabao”);
jedis.set(user.getId().getBytes(), SerializeUtils.serialize(user));
byte[] bytes=jedis.get(user.getId().getBytes()); System.out.println((User)SerializeUtils.deSerialize(bytes)); jedis.close();
|