`
ssxxjjii
  • 浏览: 931551 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Redis 存储List对象

 
阅读更多

http://blog.csdn.net/gstormspire/article/details/7653095

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

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

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

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

 

  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.   
  9. import java.io.*;  
  10. import java.util.ArrayList;  
  11. import java.util.List;  
  12. import java.util.Random;  
  13.   
  14. /** 
  15.  * Created by IntelliJ IDEA. 
  16.  * User: lifeng.xu 
  17.  * Date: 12-6-11 
  18.  * Time: 上午11:10 
  19.  * To change this template use File | Settings | File Templates. 
  20.  */  
  21. public class JedisTest {  
  22.   
  23.     private static Logger logger = LoggerFactory.getLogger(JedisTest.class);  
  24.   
  25.     /** 
  26.      * Jedis Pool for Jedis Resource 
  27.      * @return 
  28.      */  
  29.     public static JedisPool buildJedisPool(){  
  30.         JedisPoolConfig config = new JedisPoolConfig();  
  31.         config.setMaxActive(1);  
  32.         config.setMinIdle(50);  
  33.         config.setMaxIdle(3000);  
  34.         config.setMaxWait(5000);  
  35.         JedisPool jedisPool = new JedisPool(config,  
  36.                 "*****", ****);  
  37.         return jedisPool;  
  38.     }  
  39.   
  40.     /** 
  41.      * Test Data 
  42.      * @return 
  43.      */  
  44.     public static List<User> buildTestData(){  
  45.         User a = new User();  
  46.         a.setName("a");  
  47.         User b = new User();  
  48.         b.setName("b");  
  49.         List<User> list = new ArrayList<User>();  
  50.         list.add(a);  
  51.         list.add(b);  
  52.         return list;  
  53.     }  
  54.   
  55.     /** 
  56.      * Test for 
  57.      */  
  58.     public static void testSetElements(){  
  59.         List<User> testData = buildTestData();  
  60.         Jedis jedis = buildJedisPool().getResource();  
  61.         String key = "testSetElements" + new Random(1000).nextInt();  
  62.         jedis.set(key.getBytes(), ObjectsTranscoder.serialize(testData));  
  63.   
  64.         //验证   
  65.         byte[] in = jedis.get(key.getBytes());  
  66.         List<User> list = ObjectsTranscoder.deserialize(in);  
  67.         for(User user : list){  
  68.             System.out.println("testSetElements user name is:" + user.getName());  
  69.         }  
  70.     }  
  71.   
  72.     public static void testSetEnsemble(){  
  73.         List<User> testData = buildTestData();  
  74.         Jedis jedis = buildJedisPool().getResource();  
  75.         String key = "testSetEnsemble" + new Random(1000).nextInt();  
  76.         jedis.set(key.getBytes(), ListTranscoder.serialize(testData));  
  77.   
  78.         //验证   
  79.         byte[] in = jedis.get(key.getBytes());  
  80.         List<User> list = (List<User>)ListTranscoder.deserialize(in);  
  81.         for(User user : list){  
  82.             System.out.println("testSetEnsemble user name is:" + user.getName());  
  83.         }  
  84.     }  
  85.   
  86.     public static void main(String[] args) {  
  87.         testSetElements();  
  88.         testSetEnsemble();  
  89.     }  
  90.   
  91.     public static void close(Closeable closeable) {  
  92.         if (closeable != null) {  
  93.             try {  
  94.                 closeable.close();  
  95.             } catch (Exception e) {  
  96.                 logger.info("Unable to close %s", closeable, e);  
  97.             }  
  98.         }  
  99.     }  
  100.   
  101.     static class User implements Serializable{  
  102.         String name;  
  103.   
  104.         public String getName() {  
  105.             return name;  
  106.         }  
  107.   
  108.         public void setName(String name) {  
  109.             this.name = name;  
  110.         }  
  111.     }  
  112.   
  113.     static class ObjectsTranscoder{  
  114.           
  115.         public static byte[] serialize(List<User> value) {  
  116.             if (value == null) {  
  117.                 throw new NullPointerException("Can't serialize null");  
  118.             }  
  119.             byte[] rv=null;  
  120.             ByteArrayOutputStream bos = null;  
  121.             ObjectOutputStream os = null;  
  122.             try {  
  123.                 bos = new ByteArrayOutputStream();  
  124.                 os = new ObjectOutputStream(bos);  
  125.                 for(User user : value){  
  126.                     os.writeObject(user);  
  127.                 }  
  128.                 os.writeObject(null);  
  129.                 os.close();  
  130.                 bos.close();  
  131.                 rv = bos.toByteArray();  
  132.             } catch (IOException e) {  
  133.                 throw new IllegalArgumentException("Non-serializable object", e);  
  134.             } finally {  
  135.                 close(os);  
  136.                 close(bos);  
  137.             }  
  138.             return rv;  
  139.         }  
  140.   
  141.         public static List<User> deserialize(byte[] in) {  
  142.             List<User> list = new ArrayList<User>();  
  143.             ByteArrayInputStream bis = null;  
  144.             ObjectInputStream is = null;  
  145.             try {  
  146.                 if(in != null) {  
  147.                     bis=new ByteArrayInputStream(in);  
  148.                     is=new ObjectInputStream(bis);  
  149.                     while (true) {  
  150.                         User user = (User) is.readObject();  
  151.                         if(user == null){  
  152.                             break;  
  153.                         }else{  
  154.                             list.add(user);  
  155.                         }  
  156.                     }  
  157.                     is.close();  
  158.                     bis.close();  
  159.                 }  
  160.             } catch (IOException e) {  
  161.                 logger.warn("Caught IOException decoding %d bytes of data",  
  162.                         in == null ? 0 : in.length, e);  
  163.             } catch (ClassNotFoundException e) {  
  164.                 logger.warn("Caught CNFE decoding %d bytes of data",  
  165.                         in == null ? 0 : in.length, e);  
  166.             } finally {  
  167.                 CloseUtil.close(is);  
  168.                 CloseUtil.close(bis);  
  169.             }  
  170.             return list;  
  171.         }  
  172.     }  
  173.       
  174.     static class ListTranscoder{  
  175.         public static byte[] serialize(Object value) {  
  176.             if (value == null) {  
  177.                 throw new NullPointerException("Can't serialize null");  
  178.             }  
  179.             byte[] rv=null;  
  180.             ByteArrayOutputStream bos = null;  
  181.             ObjectOutputStream os = null;  
  182.             try {  
  183.                 bos = new ByteArrayOutputStream();  
  184.                 os = new ObjectOutputStream(bos);  
  185.                 os.writeObject(value);  
  186.                 os.close();  
  187.                 bos.close();  
  188.                 rv = bos.toByteArray();  
  189.             } catch (IOException e) {  
  190.                 throw new IllegalArgumentException("Non-serializable object", e);  
  191.             } finally {  
  192.                 close(os);  
  193.                 close(bos);  
  194.             }  
  195.             return rv;  
  196.         }  
  197.   
  198.         public static Object deserialize(byte[] in) {  
  199.             Object rv=null;  
  200.             ByteArrayInputStream bis = null;  
  201.             ObjectInputStream is = null;  
  202.             try {  
  203.                 if(in != null) {  
  204.                     bis=new ByteArrayInputStream(in);  
  205.                     is=new ObjectInputStream(bis);  
  206.                     rv=is.readObject();  
  207.                     is.close();  
  208.                     bis.close();  
  209.                 }  
  210.             } catch (IOException e) {  
  211.                 logger.warn("Caught IOException decoding %d bytes of data",  
  212.                         in == null ? 0 : in.length, e);  
  213.             } catch (ClassNotFoundException e) {  
  214.                 logger.warn("Caught CNFE decoding %d bytes of data",  
  215.                         in == null ? 0 : in.length, e);  
  216.             } finally {  
  217.                 CloseUtil.close(is);  
  218.                 CloseUtil.close(bis);  
  219.             }  
  220.             return rv;  
  221.         }  
  222.     }  
  223. }  
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;
        }
    }
}

 

 

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

分享到:
评论

相关推荐

    Redis如何存储对象与集合示例详解

    和Memcached类似,它支持存储的value类型相对更多,包括string(字符串)、list(链表)、set(集合)、 zset(sorted set --有序集合)和hash(哈希类型)本文介绍了关于Redis是如何存储对象与集合的相关资料,需要的朋友...

    spring集成redis,配置加代码例子

    springmvc框架加redis集成,redis直接在配置文件配置即可使用,实现了string,list,hashmap以及对象存储,将对象序列化成二进制格式存储,取出将二进制反序列化,代码有描述及例子

    Redis帮助类,为基本的设置数据和取数据

    * servicestack.redis为github中的开源项目 * redis是一个典型的k/v型数据库 * redis共支持五种类型的数据 string,list,hash,set,sortedset * * string是最简单的字符串类型 * * list是字符串列表,其内部是...

    redis-7.0.10.tar.gz

    7. 将 ziplist 替换为 Hash、List、Zset 中的 listpack。 8. 添加对列表类型的支持以存储大于 4GB 的元素 。 9. 重用模块阻塞客户端的临时客户端对象 。 10. 删除命令参数计数限制,动态增加 argv 缓冲区 。 11. ...

    Python操作redis和mongoDB的方法

    redis是一个key-value存储系统,value的类型包括string(字符串),list(链表),set(集合),zset(有序集合),hash(哈希类型)。为了保证效率,数据都是缓冲在内存中,在处理大规模数据读写的场景下运用比较多。 备注:...

    redis:redis相关操作example

    Redis提供键值对的形式对数据进行存储。支持五种数据类型:String(字符串),List(链表),Hash(散列),Set(无序集合),ZSet(有序集合)。 结构类型 结构存储的值 结构的读写能力 String 可以是字符串、整数...

    详解Redis 数据类型

    Redis支持五种数据类型:string(字符串),hash(哈希),list(列表),set(集合)及zset(sorted set:有序集合)。 String(字符串) string 是 redis 最基本的类型,你可以理解成与 Memcached 一模一样的类型,...

    Redis大key多key拆分实现方法解析

    2:hash, set,zset,list 中存储过多的元素(以万为单位) 3:一个集群存储了上亿的key,Key 本身过多也带来了更多的空间占用 (如无意外,文章中所提及的hash,set等数据结构均指redis中的数据结构 ) 由于redis...

    Redis缓存数据库详解

    1)String2)Hash3)List4)Set5)Sortedset在具体描述这几种数据类型之前,我们先通过一张图了解下Redis内部内存管理中是如何描述这些不同数据类型的:首先Redis内部使用一个redisObject对象来表示所有的key和value...

    Redis 数据类型

    Redis支持五种数据类型:string(字符串),hash(哈希),list(列表),set(集合)及zset(sorted set:有序集合)。 String(字符串) string 是 redis 最基本的类型,你可以理解成与 Memcached 一模一样的类型...

    Jodis:Jodis,Java对象字典服务器,就像Redis一样

    列表对象,脆弱基于java.util.List; 哈希表结构,一直基于java.util.Map; 集合结构,暂时基于java.util.Set; 有序集合结构,并基于java.util.Map和跳跃表。 单线程React器服务器 同时支持多个连接,命令执行为单...

    Redis 数据类型的详解

    Redis支持五种数据类型:string(字符串),hash(哈希),list(列表),set(集合)及zset(sorted set:有序集合)。 String(字符串) string是redis最基本的类型,你可以理解成与Memcached一模一样的类型,一个...

    raspberry_pi_temp:在带记录的树莓派上使用温度传感器的示例

    诸如redis-collections模块之类的模块提供Redis List对象,该对象提供Python之类的List对象,这些对象将其数据存储在Redis中。 它不会使Flash / SD卡磨损。默认情况下,每次添加新信息时,Redis不会将数据写入闪存...

    基于SpringBoot的重庆旅游推荐网站+源代码+文档说明

    图片使用腾讯云提供的对象存储方式进行存储。 ### 注意事项 **使用请替换邮箱服务以及图片云存储** ## 项目备注 1、该资源内项目代码都经过测试运行成功,功能ok的情况下才上传的,请放心下载使用! 2、本...

    免费分享 Java面试笔记 面试八股文 计算机网络基础

    Java基础:Java概念、基础语法、面向对象的理解、String类、Object类、序列化、泛型、注解与反射、JDK1.8新特性等;Java集合:List底层实现、Map底层实现等;Java并发编程:ThreadLocal、Java内存模型、锁、并发工具...

    java面试题,180多页,绝对良心制作,欢迎点评,涵盖各种知识点,排版优美,阅读舒心

    【Redis】Redis的存储结构,或者说如何工作的,与mysql的区别?有哪些数据类型? 133 【Redis】项目中用到redis,为什么选用redis 133 独特的键值对模型 134 内存储存,速度极快 135 丰富的附加功能 136 完善的文档 ...

    java开源包1

    使用redis作缓存时,支持list类型的高级数据结构,更适合论坛帖子列表这种类型的数据 5. 支持混合使用redis缓存和memcached缓存。可以将列表数据缓存到redis中,其他kv结构数据继续缓存到memcached 6. 支持redis的...

    java开源包11

    使用redis作缓存时,支持list类型的高级数据结构,更适合论坛帖子列表这种类型的数据 5. 支持混合使用redis缓存和memcached缓存。可以将列表数据缓存到redis中,其他kv结构数据继续缓存到memcached 6. 支持redis的...

    java开源包2

    使用redis作缓存时,支持list类型的高级数据结构,更适合论坛帖子列表这种类型的数据 5. 支持混合使用redis缓存和memcached缓存。可以将列表数据缓存到redis中,其他kv结构数据继续缓存到memcached 6. 支持redis的...

    java开源包3

    使用redis作缓存时,支持list类型的高级数据结构,更适合论坛帖子列表这种类型的数据 5. 支持混合使用redis缓存和memcached缓存。可以将列表数据缓存到redis中,其他kv结构数据继续缓存到memcached 6. 支持redis的...

Global site tag (gtag.js) - Google Analytics