zoukankan      html  css  js  c++  java
  • java对象序列化和反序列化,redis存入和获取对象

    最近使用redis发现直接存储序列化后的对象更方便,现提供java序列化和反序列化的代码

    1.序列化代码:

        public static byte[] serialize(Object object) {
            ObjectOutputStream oos = null;
            ByteArrayOutputStream baos = null;
            try {
                //序列化
                baos = new ByteArrayOutputStream();
                oos = new ObjectOutputStream(baos);
                oos.writeObject(object);
                byte[] bytes = baos.toByteArray();
                return bytes;
            } catch (Exception e) {
                
            }
            return null;
        }

    2.反序列化代码:

    public static Object unserialize(byte[] bytes) {
        ByteArrayInputStream bais = null;
        try {
            //反序列化
            bais = new ByteArrayInputStream(bytes);
            ObjectInputStream ois = new ObjectInputStream(bais);
            return ois.readObject();
        } catch (Exception e) {
         
        }
            return null;
        }

    3.向redis中存入序列化后的对象

    public static void setObject(Jedis jedis,int index,String key,Object obj) throws Exception {
            redisFactory.setBytes(jedis,index,key.getBytes(), SerializeUtil.serialize(obj));
            
        }

    4.从redis获取对象

        public static Object getObject(Jedis jedis,int index,String key) throws Exception {
            byte[] objSer = redisFactory.getBytes(jedis,index,key.getBytes());
            return SerializeUtil.unserialize(objSer);
        }
  • 相关阅读:
    hdu 5171(矩阵快速幂,递推)
    hdu 1316(大整数)
    hdu 5170(数学)
    hdu 5167(dfs)
    hdu 5166(水题)
    hdu 5720(贪心+区间合并)
    BestCoder 2nd Anniversary的前两题
    hdu 3065(AC自动机)
    2.3绘制构造线与射线
    查找ARP攻击源
  • 原文地址:https://www.cnblogs.com/fengyefeiluo/p/5010585.html
Copyright © 2011-2022 走看看