阅读背景:

在spring data jpa中使用redis的通用list及entity存储方法

来源:互联网 
 /**
     * 从redis中获取对象。注意:未进行haskey检测
     * 
     * @param e
     * @param redis
     * @param KEY
     * @param KEY_LIST
     * @param INDEX
     * @return
     * @version 1.0
     * @since Service 1.0
     * @date 2014年2月11日 上午10:59:06
     */
    public static <E extends IdEntity> List<E> getList(Class<E> e, RedisClient redis, String KEY, String KEY_LIST, String INDEX) {
        List<E> objects = Lists.newArrayList();
        for (Long l : ListUtil.NotNullList(redis.getList(KEY_LIST + INDEX))) {
            if (redis.hasKey(KEY + l)) {
                objects.add(redis.getEntity(e, KEY + l));
            }
        }
        return objects;
    }

    /**
     * 在reids中注入缓存对象
     * 
     * @param objects
     * @param redis
     * @param KEY
     * @param KEY_LIST
     * @param INDEX
     * @return
     * @version 1.0
     * @since Service 1.0
     * @date 2014年2月11日 上午10:59:50
     */
    public static <E extends IdEntity> List<E> creatList(List<E> objects, RedisClient redis, String KEY, String KEY_LIST, String INDEX) {
        List<E> list = ListUtil.NotNullList(objects);
        for (E e : list) {
            redis.addList(KEY_LIST + INDEX, e.getId());
            redis.saveEntity(KEY, e);
        }
        return list;
    }

    /**
     * 获取一个特定的实体类。如果redis中不存在,则从数据中获取
     * 
     * @param e
     * @param redis
     * @param dao
     * @param KEY
     * @param id
     * @return
     * @version 1.0
     * @since Service 1.0
     * @date 2014年2月11日 上午11:00:21
     */
    public static <E extends IdEntity> E getEntity(Class<E> e, RedisClient redis, CrudRepository<E, Long> dao, String KEY, Long id) {
        if (redis.hasKey(KEY + id)) {
            return BeanUtil.convertMap(e, redis.getHashOPS().entries(KEY + id));
        } else {
            synchronized (KEY) {
                if (redis.hasKey(KEY + id)) {
                    return getEntity(e, redis, dao, KEY, id);
                } else {
                    E entity = dao.findOne(id);
                    if (entity != null) {
                        redis.saveEntity(KEY, entity);
                    }
                    return entity;
                }
            }
        }
    } /**
     * 从redis中获取对象。注意:未进行haskey检测
     * 



你的当前访问异常,请进行认证后继续阅读剩余内容。

分享到: