---
title: "Redis 存储List对象 "
author: "ssxxjjii"
date: "2013-01-26T22:33:53Z"
tags: []
categories: ["互联网"]
slug: "redis-list"
draft: false
lastmod: "2013-01-26T22:33:53Z"
id: 1776213
url: "https://tdcq.iteye.com/blog/1776213"
---

[http://blog.csdn.net/gstormspire/article/details/7653095](http://blog.csdn.net/gstormspire/article/details/7653095)

如果需要用到Redis存储List对象，而list又不需要进行操作，可以按照MC的方式进行存储，不过Jedis之类的客户端没有提供API，可以有两种思路实现：

1.      分别序列化 elements ,然后 set 存储

2.    序列化List对象，set存储

这两种方法都类似MC的 Object方法存储，运用这种方式意味着放弃Redis对List提供的操作方法。

 

**\[java]** [view plain](http://blog.csdn.net/gstormspire/article/details/7653095 "view plain")[copy](http://blog.csdn.net/gstormspire/article/details/7653095 "copy")[print](http://blog.csdn.net/gstormspire/article/details/7653095 "print")[?](http://blog.csdn.net/gstormspire/article/details/7653095 "?")

001. import net.spy.memcached.compat.CloseUtil;
002. import net.spy.memcached.compat.log.Logger;
003. import net.spy.memcached.compat.log.LoggerFactory;
004. import redis.clients.jedis.Client;
005. import redis.clients.jedis.Jedis;
006. import redis.clients.jedis.JedisPool;
007. import redis.clients.jedis.JedisPoolConfig;
008. import java.io.\*;
009. import java.util.ArrayList;
010. import java.util.List;
011. import java.util.Random;
012. /\**
013. * Created by IntelliJ IDEA.
014. * User: lifeng.xu
015. * Date: 12-6-11
016. * Time: 上午11:10
017. * To change this template use File | Settings | File Templates.
018. \*/
019. public class JedisTest {
020. private static Logger logger = LoggerFactory.getLogger(JedisTest.class);
021. /\**
022. * Jedis Pool for Jedis Resource
023. * @return
024. \*/
025. public static JedisPool buildJedisPool(){
026. JedisPoolConfig config = new JedisPoolConfig();
027. config.setMaxActive(1);
028. config.setMinIdle(50);
029. config.setMaxIdle(3000);
030. config.setMaxWait(5000);
031. JedisPool jedisPool = new JedisPool(config,
032. "\*\*\*\*\*", \*\*\*\*);
033. return jedisPool;
034. }
035. /\**
036. * Test Data
037. * @return
038. \*/
039. public static List&lt;User&gt; buildTestData(){
040. User a = new User();
041. a.setName("a");
042. User b = new User();
043. b.setName("b");
044. List&lt;User&gt; list = new ArrayList&lt;User&gt;();
045. list.add(a);
046. list.add(b);
047. return list;
048. }
049. /\**
050. * Test for
051. \*/
052. public static void testSetElements(){
053. List&lt;User&gt; testData = buildTestData();
054. Jedis jedis = buildJedisPool().getResource();
055. String key = "testSetElements" + new Random(1000).nextInt();
056. jedis.set(key.getBytes(), ObjectsTranscoder.serialize(testData));
057. //验证
058. byte\[] in = jedis.get(key.getBytes());
059. List&lt;User&gt; list = ObjectsTranscoder.deserialize(in);
060. for(User user : list){
061. System.out.println("testSetElements user name is:" + user.getName());
062. }
063. }
064. public static void testSetEnsemble(){
065. List&lt;User&gt; testData = buildTestData();
066. Jedis jedis = buildJedisPool().getResource();
067. String key = "testSetEnsemble" + new Random(1000).nextInt();
068. jedis.set(key.getBytes(), ListTranscoder.serialize(testData));
069. //验证
070. byte\[] in = jedis.get(key.getBytes());
071. List&lt;User&gt; list = (List&lt;User&gt;)ListTranscoder.deserialize(in);
072. for(User user : list){
073. System.out.println("testSetEnsemble user name is:" + user.getName());
074. }
075. }
076. public static void main(String\[] args) {
077. testSetElements();
078. testSetEnsemble();
079. }
080. public static void close(Closeable closeable) {
081. if (closeable != null) {
082. try {
083. closeable.close();
084. } catch (Exception e) {
085. logger.info("Unable to close %s", closeable, e);
086. }
087. }
088. }
089. static class User implements Serializable{
090. String name;
091. public String getName() {
092. return name;
093. }
094. public void setName(String name) {
095. this.name = name;
096. }
097. }
098. static class ObjectsTranscoder{
099. public static byte\[] serialize(List&lt;User&gt; value) {
100. if (value == null) {
101. throw new NullPointerException("Can't serialize null");
102. }
103. byte\[] rv=null;
104. ByteArrayOutputStream bos = null;
105. ObjectOutputStream os = null;
106. try {
107. bos = new ByteArrayOutputStream();
108. os = new ObjectOutputStream(bos);
109. for(User user : value){
110. os.writeObject(user);
111. }
112. os.writeObject(null);
113. os.close();
114. bos.close();
115. rv = bos.toByteArray();
116. } catch (IOException e) {
117. throw new IllegalArgumentException("Non-serializable object", e);
118. } finally {
119. close(os);
120. close(bos);
121. }
122. return rv;
123. }
124. public static List&lt;User&gt; deserialize(byte\[] in) {
125. List&lt;User&gt; list = new ArrayList&lt;User&gt;();
126. ByteArrayInputStream bis = null;
127. ObjectInputStream is = null;
128. try {
129. if(in != null) {
130. bis=new ByteArrayInputStream(in);
131. is=new ObjectInputStream(bis);
132. while (true) {
133. User user = (User) is.readObject();
134. if(user == null){
135. break;
136. }else{
137. list.add(user);
138. }
139. }
140. is.close();
141. bis.close();
142. }
143. } catch (IOException e) {
144. logger.warn("Caught IOException decoding %d bytes of data",
145. in == null ? 0 : in.length, e);
146. } catch (ClassNotFoundException e) {
147. logger.warn("Caught CNFE decoding %d bytes of data",
148. in == null ? 0 : in.length, e);
149. } finally {
150. CloseUtil.close(is);
151. CloseUtil.close(bis);
152. }
153. return list;
154. }
155. }
156. static class ListTranscoder{
157. public static byte\[] serialize(Object value) {
158. if (value == null) {
159. throw new NullPointerException("Can't serialize null");
160. }
161. byte\[] rv=null;
162. ByteArrayOutputStream bos = null;
163. ObjectOutputStream os = null;
164. try {
165. bos = new ByteArrayOutputStream();
166. os = new ObjectOutputStream(bos);
167. os.writeObject(value);
168. os.close();
169. bos.close();
170. rv = bos.toByteArray();
171. } catch (IOException e) {
172. throw new IllegalArgumentException("Non-serializable object", e);
173. } finally {
174. close(os);
175. close(bos);
176. }
177. return rv;
178. }
179. public static Object deserialize(byte\[] in) {
180. Object rv=null;
181. ByteArrayInputStream bis = null;
182. ObjectInputStream is = null;
183. try {
184. if(in != null) {
185. bis=new ByteArrayInputStream(in);
186. is=new ObjectInputStream(bis);
187. rv=is.readObject();
188. is.close();
189. bis.close();
190. }
191. } catch (IOException e) {
192. logger.warn("Caught IOException decoding %d bytes of data",
193. in == null ? 0 : in.length, e);
194. } catch (ClassNotFoundException e) {
195. logger.warn("Caught CNFE decoding %d bytes of data",
196. in == null ? 0 : in.length, e);
197. } finally {
198. CloseUtil.close(is);
199. CloseUtil.close(bis);
200. }
201. return rv;
202. }
203. }
204. }

```
import net.spy.memcached.compat.CloseUtil;
import net.spy.memcached.compat.log.Logger;
import net.spy.memcached.compat.log.LoggerFactory;
import redis.clients.jedis.Client;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * Created by IntelliJ IDEA.
 * User: lifeng.xu
 * Date: 12-6-11
 * Time: 上午11:10
 * To change this template use File | Settings | File Templates.
 */
public class JedisTest {

    private static Logger logger = LoggerFactory.getLogger(JedisTest.class);

    /**
     * Jedis Pool for Jedis Resource
     * @return
     */
    public static JedisPool buildJedisPool(){
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxActive(1);
        config.setMinIdle(50);
        config.setMaxIdle(3000);
        config.setMaxWait(5000);
        JedisPool jedisPool = new JedisPool(config,
                "*****", ****);
        return jedisPool;
    }

    /**
     * Test Data
     * @return
     */
    public static List<User> buildTestData(){
        User a = new User();
        a.setName("a");
        User b = new User();
        b.setName("b");
        List<User> list = new ArrayList<User>();
        list.add(a);
        list.add(b);
        return list;
    }

    /**
     * Test for
     */
    public static void testSetElements(){
        List<User> testData = buildTestData();
        Jedis jedis = buildJedisPool().getResource();
        String key = "testSetElements" + new Random(1000).nextInt();
        jedis.set(key.getBytes(), ObjectsTranscoder.serialize(testData));

        //验证
        byte[] in = jedis.get(key.getBytes());
        List<User> list = ObjectsTranscoder.deserialize(in);
        for(User user : list){
            System.out.println("testSetElements user name is:" + user.getName());
        }
    }

    public static void testSetEnsemble(){
        List<User> testData = buildTestData();
        Jedis jedis = buildJedisPool().getResource();
        String key = "testSetEnsemble" + new Random(1000).nextInt();
        jedis.set(key.getBytes(), ListTranscoder.serialize(testData));

        //验证
        byte[] in = jedis.get(key.getBytes());
        List<User> list = (List<User>)ListTranscoder.deserialize(in);
        for(User user : list){
            System.out.println("testSetEnsemble user name is:" + user.getName());
        }
    }

    public static void main(String[] args) {
        testSetElements();
        testSetEnsemble();
    }

    public static void close(Closeable closeable) {
        if (closeable != null) {
            try {
                closeable.close();
            } catch (Exception e) {
                logger.info("Unable to close %s", closeable, e);
            }
        }
    }

    static class User implements Serializable{
        String name;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }

    static class ObjectsTranscoder{
        
        public static byte[] serialize(List<User> value) {
            if (value == null) {
                throw new NullPointerException("Can't serialize null");
            }
            byte[] rv=null;
            ByteArrayOutputStream bos = null;
            ObjectOutputStream os = null;
            try {
                bos = new ByteArrayOutputStream();
                os = new ObjectOutputStream(bos);
                for(User user : value){
                    os.writeObject(user);
                }
                os.writeObject(null);
                os.close();
                bos.close();
                rv = bos.toByteArray();
            } catch (IOException e) {
                throw new IllegalArgumentException("Non-serializable object", e);
            } finally {
                close(os);
                close(bos);
            }
            return rv;
        }

        public static List<User> deserialize(byte[] in) {
            List<User> list = new ArrayList<User>();
            ByteArrayInputStream bis = null;
            ObjectInputStream is = null;
            try {
                if(in != null) {
                    bis=new ByteArrayInputStream(in);
                    is=new ObjectInputStream(bis);
                    while (true) {
                        User user = (User) is.readObject();
                        if(user == null){
                            break;
                        }else{
                            list.add(user);
                        }
                    }
                    is.close();
                    bis.close();
                }
            } catch (IOException e) {
                logger.warn("Caught IOException decoding %d bytes of data",
                        in == null ? 0 : in.length, e);
            } catch (ClassNotFoundException e) {
                logger.warn("Caught CNFE decoding %d bytes of data",
                        in == null ? 0 : in.length, e);
            } finally {
                CloseUtil.close(is);
                CloseUtil.close(bis);
            }
            return list;
        }
    }
    
    static class ListTranscoder{
        public static byte[] serialize(Object value) {
            if (value == null) {
                throw new NullPointerException("Can't serialize null");
            }
            byte[] rv=null;
            ByteArrayOutputStream bos = null;
            ObjectOutputStream os = null;
            try {
                bos = new ByteArrayOutputStream();
                os = new ObjectOutputStream(bos);
                os.writeObject(value);
                os.close();
                bos.close();
                rv = bos.toByteArray();
            } catch (IOException e) {
                throw new IllegalArgumentException("Non-serializable object", e);
            } finally {
                close(os);
                close(bos);
            }
            return rv;
        }

        public static Object deserialize(byte[] in) {
            Object rv=null;
            ByteArrayInputStream bis = null;
            ObjectInputStream is = null;
            try {
                if(in != null) {
                    bis=new ByteArrayInputStream(in);
                    is=new ObjectInputStream(bis);
                    rv=is.readObject();
                    is.close();
                    bis.close();
                }
            } catch (IOException e) {
                logger.warn("Caught IOException decoding %d bytes of data",
                        in == null ? 0 : in.length, e);
            } catch (ClassNotFoundException e) {
                logger.warn("Caught CNFE decoding %d bytes of data",
                        in == null ? 0 : in.length, e);
            } finally {
                CloseUtil.close(is);
                CloseUtil.close(bis);
            }
            return rv;
        }
    }
}
```

 

 

PS：Redsi中存储list没有封装对Object的API，是不是也是倾向于只存储用到的字段，而不是存储Object本身呢？Redis是一个In-Mem的产品，会觉得我们应用的方式。