0%

将对象存在REDIS序列化

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 {
//将obj转成byte[]数组 序列化
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;
}
//将byte[]数组转成obj 反序列化
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”);
//把一个对象存入进去,其中id作为key,后面的对象序列化成byte字节
jedis.set(user.getId().getBytes(), SerializeUtils.serialize(user));
//先取出key,再取出values 从redis取出来将序列化的数组转成对象
byte[] bytes=jedis.get(user.getId().getBytes());
System.out.println((User)SerializeUtils.deSerialize(bytes));
jedis.close();