您的位置:首页 > 数据库 > Redis

redis java对象操作

2013-08-02 11:33 393 查看
使用Jedis客户端

1. java 对象,需序列化

public class Person implements Serializable {

private int id;

private String name;

public Person(int id, String name) {

this.id = id;

this.name = name;

}

public int getId() {

return id;

}

public String getName() {

return name;

}


2. 序列化类

public class SerializeUtil {

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;

}

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. 对象的操作测试

public class SerializeTest {

/**
* @param args
*/
private static Jedis jedis;
public static void main(String[] args) throws InterruptedException {
jedis=new Jedis("127.0.0.1",6379);
setObject();
Thread.sleep(1000);
Person person =getObject(100);
System.out.println(jedis.keys("*"));
if(person!=null){
System.out.println(person.getId());

System.out.println(person.getName());
}

delOject();
System.out.println(jedis.keys("*"));
person = getObject(100);
if(person!=null){
System.out.println(person.getId());

System.out.println(person.getName());
}else{
System.out.println("key not exist");
}

}
public static Person getObject(int id) {

byte[] person = jedis.get(("person:" + id).getBytes());

return (Person) SerializeUtil.unserialize(person);

}

public static void setObject() {

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));

}

public static void delOject(){
boolean isExist=jedis.exists("person:100".getBytes());
if(isExist){
System.out.println("delete the key");
jedis.del("person:100".getBytes());
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: