Redis儲存Object 和 list<object>

來源:互聯網
上載者:User

標籤:redis   jedis   redis儲存object   

Redis 儲存支援的類型沒有object ,雖然有支援list,但是只支援List<String>

有兩種方法可以實現儲存物件和泛型

1.用序列化和還原序列化

2.json


序列化工具類,實現序列化和反序列話對象和list集合

package com;import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.Closeable;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.util.ArrayList;import java.util.List;/** * 序列化工具類 * @author caspar * */public class SerializeUtil {/** * 序列化 * @param object * @return */public static byte[] serialize(Object object) {if (object == null) {return null;}ObjectOutputStream oos = null;ByteArrayOutputStream baos = null;byte[] bytes = null;try {// 序列化baos = new ByteArrayOutputStream();oos = new ObjectOutputStream(baos);oos.writeObject(object);bytes = baos.toByteArray();} catch (Exception e) {e.printStackTrace();} finally {close(oos);close(baos);}return bytes;}/** * 還原序列化 *  * @param bytes * @return */public static Object unserialize(byte[] bytes) {if (bytes == null) {return null;}ByteArrayInputStream bais = null;ObjectInputStream ois = null;try {// 還原序列化bais = new ByteArrayInputStream(bytes);ois = new ObjectInputStream(bais);return ois.readObject();} catch (Exception e) {e.printStackTrace();} finally {close(bais);close(ois);}return null;}/** * 序列化 list 集合 *  * @param list * @return */public static byte[] serializeList(List<?> list) {if (CommonUtil.isEmptyList(list)) {return null;}ObjectOutputStream oos = null;ByteArrayOutputStream baos = null;byte[] bytes = null;try {baos = new ByteArrayOutputStream();oos = new ObjectOutputStream(baos);for (Object obj : list) {oos.writeObject(obj);}bytes = baos.toByteArray();} catch (Exception e) {e.printStackTrace();} finally {close(oos);close(baos);}return bytes;}/** * 還原序列化 list 集合 *  * @param lb * @return */public static List<?> unserializeList(byte[] bytes) {if (bytes == null) {return null;}List<Object> list = new ArrayList<Object>();ByteArrayInputStream bais = null;ObjectInputStream ois = null;try {// 還原序列化bais = new ByteArrayInputStream(bytes);ois = new ObjectInputStream(bais);while (bais.available() > 0) {Object obj = (Object) ois.readObject();if (obj == null) {break;}list.add(obj);}} catch (Exception e) {e.printStackTrace();} finally {close(bais);close(ois);}return list;}/** * 關閉io流對象 *  * @param closeable */public static void close(Closeable closeable) {if (closeable != null) {try {closeable.close();} catch (Exception e) {e.printStackTrace();}}}}

redis工具類的部分方法,實現設定/擷取對象和泛型值

 /**     * 設定對象     * @param key     * @param obj     */    public static void setObject(String key ,Object obj){    try {    obj = obj == null ? new Object():obj;    getJedis().set(key.getBytes(), SerializeUtil.serialize(obj));} catch (Exception e) {e.printStackTrace();}}        /**     * 擷取對象     * @param key     * @return Object     */public static Object getObject(String key){if(getJedis() == null || !getJedis().exists(key)){return null;}byte[] data = getJedis().get(key.getBytes());return (Object)SerializeUtil.unserialize(data);}/**     * 設定List集合     * @param key     * @param list     */    public static void setList(String key ,List<?> list){    try {        if(CommonUtil.isNotEmptyList(list)){    getJedis().set(key.getBytes(), SerializeUtil.serializeList(list));    }else{//如果list為空白,則設定一個空    getJedis().set(key.getBytes(), "".getBytes());    }} catch (Exception e) {e.printStackTrace();}}    /**     * 擷取List集合     * @param key     * @return     */public static List<?> getList(String key){if(getJedis() == null || !getJedis().exists(key)){return null;}byte[] data = getJedis().get(key.getBytes());return SerializeUtil.unserializeList(data);}


測試main方法

public static void main(String[] args) {    //object    setObject("100",new Person("caspar",25));        Person p = (Person)getObject("100");    System.out.println(p.getName()+"----"+p.getAge());        //list    List<Person> list = new ArrayList<Person>();    list.add(new Person("唐馬儒",39));    list.add(new Person("大便熊",33));    list.add(new Person("小蘿莉",14));        setList("list001", list);    List<Person> resultList = (List<Person>) getList("list001");    for (Person person : resultList) {System.out.println(person.getName()+"----"+person.getAge());}}

輸出結果

caspar----25
唐馬儒----39
大便熊----33
小蘿莉----14


正常情況下效率也挺高,但是如果再高並發的情況下,序列化和還原序列化消耗太多,redis不支援儲存object和泛型,是有理由的。

建議使用json來儲存

把object和list<?> 轉成json的字串格式再set到redis裡面,取得時候再把json轉換為需要的對象,這樣簡單快捷,推薦使用





Redis儲存Object 和 list<object>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.