Redis入門 – Jedis儲存Java對象 - (Java序列化為byte數組方式)

來源:互聯網
上載者:User

標籤:

原文地址:http://alanland.iteye.com/blog/1600685

在Jedis開發中,我們很多時候希望直接把一個對象放到Redis中,然後在需要的時候取出來。Redis的key和value都支援二進位安全的字串,儲存Java對象不是問題,下面我們看一下如何來實現。

 

1要儲存的對象

現在寫一個很土的Java Bean,包含兩個欄位,id和name,類名叫做Person。為了實現序列化需求,該類實現Serializable介面。

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寫對象

將Person對象寫入Redis中:

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

}

 

運行上面代碼之後,我們到命令列視窗中讀取該對象,看看有沒有寫入成功:

redis 127.0.0.1:6379> get person:100

"\xac\xed\x00\x05sr\x00\x15alanland.redis.Person\x05\xf4\x8d9A\xf4`\xb0\x02\x00\x02I\x00\x02idL\x00\x04namet\x00\x12Ljava/lang/String;xp\x00\x00\x00dt\x00\x04alan"

 

可以取到序列化之後的值。

 

4取對象

用Jedis擷取對象:

public Person getObject(int id) {

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

return (Person) SerializeUtil.unserialize(person);

}

 

測試一下上一步存入的兩個對象:

Person person = test.getObject(100);

System.out.println(person.getId());

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

person = test.getObject(101);

System.out.println(person.getId());

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

 

Java控制台輸入:

100

alan

101

bruce

 

由此可見,序列化對象在Redis中存取正確。

 

Redis入門 – Jedis儲存Java對象 - (Java序列化為byte數組方式)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.