Redis是可以存放一個Java對象並獲取的,用到的知識點就是Java的序列化機制。
1、編寫序列化工具方法
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class SerializeUtil {
public static byte[] serialize(Object object) throws IOException {
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 {
baos.close();
oos.close();
}
return null;
}
public static Object unserialize(byte[] bytes) throws IOException {
ByteArrayInputStream bais = null;
try {
// 反序列化
bais = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bais);
return ois.readObject();
} catch (Exception e) {
e.printStackTrace();
}finally {
bais.close();
}
return null;
}
}
2、創建對象
import java.io.Serializable;
public class Person implements Serializable {
private static final long serialVersionUID = 1L;
private int no;
private String name;
public Person(int no, String name) {
super();
this.no = no;
this.name = name;
}
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
3、編寫Redis實現
import java.io.IOException;
import redis.clients.jedis.Jedis;
public class ObjectTest {
public static void main(String[] args) {
ObjectTest objectTest = new ObjectTest();
//objectTest.add();
objectTest.get();
}
public void add() {
Jedis jedis = new Jedis("localhost", 6379);
try {
Person person = new Person(100, "alan");
jedis.set("person:100".getBytes(), SerializeUtil.serialize(person));
person = new Person(101, "bruce");
jedis.set("person:101".getBytes(), SerializeUtil.serialize(person));
// redis 127.0.0.1:6379> get person:100
// "\xac\xed\x00\x05sr\x00\x15alanland.redis...
} catch (Exception e) {
e.printStackTrace();
}
}
public void get() {
Jedis jedis = new Jedis("localhost", 6379);
System.out.println(jedis.get("person:100")); // 這裏是亂碼
byte[] personRedis = jedis.get(("person:100").getBytes());
try {
Person person = (Person)SerializeUtil.unserialize(personRedis);
System.out.println(person.getNo());
System.out.println(person.getName());
} catch (IOException e) {
e.printStackTrace();
}
}
}