Redis之java操做篇(數據對象的存取)

SerializeUtil.javajava

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,新建測試對象測試

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,新建測試代碼this

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,運行查看結果code

相關文章
相關標籤/搜索