ITeye博客

Redis 存储List对象

ssxxjjii · 2013-01-26 22:33 · redis · 互联网 · Markdown

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 plaincopyprint?

  1. import net.spy.memcached.compat.CloseUtil;
  2. import net.spy.memcached.compat.log.Logger;
  3. import net.spy.memcached.compat.log.LoggerFactory;
  4. import redis.clients.jedis.Client;
  5. import redis.clients.jedis.Jedis;
  6. import redis.clients.jedis.JedisPool;
  7. import redis.clients.jedis.JedisPoolConfig;
  8. import java.io.*;
  9. import java.util.ArrayList;
  10. import java.util.List;
  11. import java.util.Random;
  12. /**
  13. * Created by IntelliJ IDEA.
  14. * User: lifeng.xu
  15. * Date: 12-6-11
  16. * Time: 上午11:10
  17. * To change this template use File | Settings | File Templates.
  18. */
  19. public class JedisTest {
  20. private static Logger logger = LoggerFactory.getLogger(JedisTest.class);
  21. /**
  22. * Jedis Pool for Jedis Resource
  23. * @return
  24. */
  25. public static JedisPool buildJedisPool(){
  26. JedisPoolConfig config = new JedisPoolConfig();
  27. config.setMaxActive(1);
  28. config.setMinIdle(50);
  29. config.setMaxIdle(3000);
  30. config.setMaxWait(5000);
  31. JedisPool jedisPool = new JedisPool(config,
  32. "*****", ****);
  33. return jedisPool;
  34. }
  35. /**
  36. * Test Data
  37. * @return
  38. */
  39. public static List<User> buildTestData(){
  40. User a = new User();
  41. a.setName("a");
  42. User b = new User();
  43. b.setName("b");
  44. List<User> list = new ArrayList<User>();
  45. list.add(a);
  46. list.add(b);
  47. return list;
  48. }
  49. /**
  50. * Test for
  51. */
  52. public static void testSetElements(){
  53. List<User> testData = buildTestData();
  54. Jedis jedis = buildJedisPool().getResource();
  55. String key = "testSetElements" + new Random(1000).nextInt();
  56. jedis.set(key.getBytes(), ObjectsTranscoder.serialize(testData));
  57. //验证
  58. byte[] in = jedis.get(key.getBytes());
  59. List<User> list = ObjectsTranscoder.deserialize(in);
  60. for(User user : list){
  61. System.out.println("testSetElements user name is:" + user.getName());
  62. }
  63. }
  64. public static void testSetEnsemble(){
  65. List<User> testData = buildTestData();
  66. Jedis jedis = buildJedisPool().getResource();
  67. String key = "testSetEnsemble" + new Random(1000).nextInt();
  68. jedis.set(key.getBytes(), ListTranscoder.serialize(testData));
  69. //验证
  70. byte[] in = jedis.get(key.getBytes());
  71. List<User> list = (List<User>)ListTranscoder.deserialize(in);
  72. for(User user : list){
  73. System.out.println("testSetEnsemble user name is:" + user.getName());
  74. }
  75. }
  76. public static void main(String[] args) {
  77. testSetElements();
  78. testSetEnsemble();
  79. }
  80. public static void close(Closeable closeable) {
  81. if (closeable != null) {
  82. try {
  83. closeable.close();
  84. } catch (Exception e) {
  85. logger.info("Unable to close %s", closeable, e);
  86. }
  87. }
  88. }
  89. static class User implements Serializable{
  90. String name;
  91. public String getName() {
  92. return name;
  93. }
  94. public void setName(String name) {
  95. this.name = name;
  96. }
  97. }
  98. static class ObjectsTranscoder{
  99. public static byte[] serialize(List<User> 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<User> deserialize(byte[] in) {
  125. List<User> list = new ArrayList<User>();
  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的产品,会觉得我们应用的方式。

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。