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);
        }
  • 相关阅读:
    ios 截图图片
    更改AlertView背景
    如何卸载编译安装的源码包(mysql卸载)
    测试6
    curl 测试websocket请求 whitesky
    JVM中的垃圾收集
    Java面试题
    Java的四种引用
    一款吊炸天的AI图片增强工具!
    LiteFlow 2.6.4版本发行注记,里程碑版本!
  • 原文地址:https://www.cnblogs.com/fengyefeiluo/p/5010585.html
Copyright © 2011-2022 走看看