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

Redis之java操作篇(数据对象的存取)

2016-01-07 00:00 681 查看
摘要: Redis本身没有存取对象的功能,而是有存取byte数据的功能,我们可以对要存取的对象进行序列化后,进行操作

SerializeUtil.java

[code=plain]public class SerializeUtil {
/**
* 序列化
* @param object
*/
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) {
e.printStackTrace();
}
return null;
}

/**
* 反序列化
* @param bytes
*/
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) {
e.printStackTrace();
}
return null;
}
}


1,新建测试对象

[code=plain]package demo.bean;

import java.io.Serializable;

public class Goods implements Serializable {
/**
*
*/
private static final long serialVersionUID = 6856239042967045162L;
private String name;
private Float price;
private String desc;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Float getPrice() {
return price;
}
public void setPrice(Float price) {
this.price = price;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}

}


2,新建测试代码

[code=plain]package demo;

import demo.bean.Goods;

public class TestObject {
public static void main (String[] args) {
Goods g1 = new Goods();
g1.setName("苹果");
g1.setPrice(5f);
g1.setDesc("这里的苹果大又甜");

Goods g2 = new Goods();
g2.setName("橘子");
g2.setPrice(3.5f);
g2.setDesc("这里的橘子水很多");

RedisUtil.getJedis().set("g1".getBytes(), SerializeUtil.serialize(g1));
byte[] bg1 = RedisUtil.getJedis().get("g1".getBytes());
Goods rg1 = (Goods)SerializeUtil.unserialize(bg1);
System.out.println(rg1.getName());
System.out.println(rg1.getPrice());
System.out.println(rg1.getDesc());
}
}

3,运行查看结果
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  redis jedis 操作对象