重庆幸运农场中奖金额|重庆幸运农场官网
MyException - 我的異常網
當前位置:我的異常網» 互聯網 » Redis 儲存List對象

Redis 儲存List對象

www.h0f1.com  網友分享于:2013-02-05  瀏覽:77次
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提供的操作方法。

?

[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. ??
  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. ?????*[email protected]?
  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. ?????*[email protected]?
  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的產品,會覺得我們應用的方式。

文章評論

軟件開發程序錯誤異常ExceptionCopyright © 2009-2015 MyException 版權所有
重庆幸运农场中奖金额