redis整合spring示例二—java操作redis(存对象及List)

2015-06-12|来源:

java操作redis中,咱们已经有了基本的java操作redis相关代码。下面继续

redis存放对象和List可通过对它们先序列化,然后存到redis中。


对象序列化及反序列化工具类:


package com._656463.redis;
   
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
   
/**
 * Jedis does not support cache the Object directly, the Objects needed to be
 * serialized and de-serialized
 */
public class ObjectTranscoder<M extends Serializable> extends
        SerializeTranscoder {
   
    @SuppressWarnings("unchecked")
    @Override
    public byte[] serialize(Object value) {
        if (value == null) {
            throw new NullPointerException("Can't serialize null");
        }
        byte[] result = null;
        ByteArrayOutputStream bos = null;
        ObjectOutputStream os = null;
        try {
            bos = new ByteArrayOutputStream();
            os = new ObjectOutputStream(bos);
            M m = (M) value;
            os.writeObject(m);
            os.close();
            bos.close();
            result = bos.toByteArray();
        } catch (IOException e) {
            throw new IllegalArgumentException("Non-serializable object", e);
        } finally {
            close(os);
            close(bos);
        }
        return result;
    }
   
    @SuppressWarnings("unchecked")
    @Override
    public M deserialize(byte[] in) {
        M result = null;
        ByteArrayInputStream bis = null;
        ObjectInputStream is = null;
        try {
            if (in != null) {
                bis = new ByteArrayInputStream(in);
                is = new ObjectInputStream(bis);
                result = (M) is.readObject();
                is.close();
                bis.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            close(is);
            close(bis);
        }
        return result;
    }
}

List序列化和反序列化工具类:


package com._656463.redis;
   
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
   
/**
 * Jedis does not support cache the Object directly, the Objects needed to be 
 * serialized and de-serialized
 *
 * @作者 : huangyineng
 * @日期 : 2015-6-11  下午5:55:21
 */
public class ListTranscoder<M extends Serializable> extends SerializeTranscoder {
   
    @SuppressWarnings("unchecked")
    public List<M> deserialize(byte[] in) {
        List<M> list = new ArrayList<M>();
        ByteArrayInputStream bis = null;
        ObjectInputStream is = null;
        try {
            if (in != null) {
                bis = new ByteArrayInputStream(in);
                is = new ObjectInputStream(bis);
                while (true) {
                    M m = (M) is.readObject();
                    if (m == null) {
                        break;
                    }
                    list.add(m);
                }
                is.close();
                bis.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            close(is);
            close(bis);
        }
   
        return list;
    }
   
    @SuppressWarnings("unchecked")
    @Override
    public byte[] serialize(Object value) {
        if (value == null) {
            throw new NullPointerException("Can't serialize null");
        }
   
        List<M> values = (List<M>) value;
   
        byte[] results = null;
        ByteArrayOutputStream bos = null;
        ObjectOutputStream os = null;
   
        try {
            bos = new ByteArrayOutputStream();
            os = new ObjectOutputStream(bos);
            for (M m : values) {
                os.writeObject(m);
            }
   
            os.writeObject(null);//不加会报java.io.EOFException异常
            os.close();
            bos.close();
            results = bos.toByteArray();
        } catch (IOException e) {
            throw new IllegalArgumentException("Non-serializable object", e);
        } finally {
            close(os);
            close(bos);
        }
   
        return results;
    }
}

抽象基类


package com._656463.redis;
   
import java.io.Closeable;
   
public abstract class SerializeTranscoder {
   
    public abstract byte[] serialize(Object value);
   
    public abstract Object deserialize(byte[] in);
   
    public void close(Closeable closeable) {
        if (closeable != null) {
            try {
                closeable.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}


看在代码中怎么调用。这可能本站使用的代码


@Resource(name = "redisClientTemplate")
private RedisClientTemplate redisClient;
   
public List<Channel> findAllChannels(){
    List<Channel> results = null;
    ListTranscoder<Channel> listTranscoder = new ListTranscoder<Channel>();
       
    byte[] channels = redisClient.get(Constants.CHANNELS_REDIES_KEY);
    if(channels!=null){
        results = listTranscoder.deserialize(channels);
    }
       
    if(results==null || results.size()<=0){
        Map<Object, Object> params = new HashMap<Object, Object>();
        params.put("start", 0);
        params.put("size",Integer.MAX_VALUE);
        results = this.findScrollDataList(params);
           
        //加入redis
        channels = listTranscoder.serialize(results);
        redisClient.set(Constants.CHANNELS_REDIES_KEY, channels);
        redisClient.setExpire(Constants.CHANNELS_REDIES_KEY, Constants.expireTime);
    }
    return results;
}


完毕


相关问答

更多

怎么在redis里面存list

将list转json或者其他string类型的字符串,再存进redis,因为redis不支持存数组或对象。

springboot整合redis为什么数据存不进redis,实现不了缓存

检查Redis配置是否正确,包括连接地址、密码、端口是否修改之类

怎么把list对象放到redis key value

1. 分别序列化 elements ,然后 set 存储 2. 序列化List对象,set存储 这两种方法都类似MC的 Object方法存储,运用这种方式意味着放弃Redis对List提供的操作方法。

java List集合与redis数据快速比对

只提供想法:前提:所要对比的数据是相同的,或者不可重复字段是相同的 ,因为list数据比较小,那么让list里面的数据插入redis 数据源里面,循环单条插入,中间需要绕过并处理好报错的,然后你就知道那些事重复的了

使用redis做数据缓存操作list问题

我一般会用 用户id+ 传的参数中的一部分+方法名 做key

专题教程

相关文章

更多

最近更新

更多