ITeye博客

redis存储对象和集合

小色帝 · 2018-09-19 22:36 · 缓存 · 企业架构 · Markdown

使用redis存储对象或集合时,不能直接存储。需要将对象或集 合通过序列化转换为可存储的json,这里使用了fastjson来转型 redis是一个key-value存储系统。和Memcached类似,它支持存储的value类型相对更多,包括string(字符串)、list(链表)、set(集合)、

   zset(sorted set --有序集合)和hash(哈希类型)

所用到的依赖,可以在maven仓库中查找

import java.util.List; import java.util.Map; import java.util.Set;

import org.apache.commons.lang.StringUtils;

import com.fasterxml.jackson.databind.ObjectMapper;

import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; import redis.clients.util.SafeEncoder;

public class jedisUtil {

    private static String HOST = "localhost";
    private static int PORT = 6379;
 
    private static JedisPool pool = null;
 
    static {
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(128);
        config.setMaxIdle(80);
        config.setMaxWaitMillis(2001);
 
            pool = new JedisPool(config, HOST, PORT, 2000);
    }
 
    /**
     * 把key存入redis中
     *
     * @param key     k
     * @param value   v
     * @param seconds 过期时间(秒)
     * @return boolean
     */
    public static boolean set(byte key, byte value, int seconds) {
        Jedis jedis = null;
        try {
            jedis = pool.getResource();
            String result = jedis.set(key, value);
            if (seconds > 0) {
                Long r = jedis.expire(key, seconds);
            }
        } catch (Exception e) {
            return false;
        } finally {
            if (null != jedis) {
                jedis.close();
            }
        }
        return true;
    }
 
    public static byte get(byte key) {
        byte value = null;
        Jedis jedis = null;
        try {
            jedis = pool.getResource();
            value = jedis.get(key);
        } catch (Exception e) {
        } finally {
            if (null != jedis) {
                jedis.close();
            }
        }
        return value;
    }
 
 
    /**
     * 向缓存中设置对象
     *
     * @param key key
     * @param obj value
     * @return boolean
     */
    public static boolean set(String key, Object obj, Integer seconds) {
        Jedis jedis = null;
        try {
            jedis = pool.getResource();
            ObjectMapper mapper = new ObjectMapper();
            String value = mapper.writeValueAsString(obj);
            jedis.set(SafeEncoder.encode(key), SafeEncoder.encode(value));
            if (seconds != null) {
                jedis.expire(key, seconds);
            }
            return true;
        } catch (Exception e) {
        } finally {
            if (null != jedis) {
                jedis.close();
            }
        }
        return false;
    }
 
 
    /**
     * 向缓存中设置对象
     *
     * @param key   key
     * @param value value
     * @return boolean
     */
    public static boolean set(String key, String value, Integer seconds) {
        Jedis jedis = null;
        try {
            jedis = pool.getResource();
            jedis.set(SafeEncoder.encode(key), SafeEncoder.encode(value));
            if (seconds != null) {
                jedis.expire(key, seconds);
            }
            return true;
        } catch (Exception e) {
        } finally {
            if (null != jedis) {
                jedis.close();
            }
        }
        return false;
    }
 
    /**
     * 移除缓存中设置对象
     *
     * @param keys 被删除的KEYS
     * @return Long 被删除个数
     */
    public static Long del(String... keys) {
        Jedis jedis = null;
        try {
            jedis = pool.getResource();
            return jedis.del(keys);
        } catch (Exception e) {
        } finally {
            if (null != jedis) {
                jedis.close();
            }
        }
        return null;
    }
 
    /**
     * 根据key 获取对象
     *
     * @param key key
     * @return T
     */
    public static <T> T get(String key, Class<T> clazz) {
        Jedis jedis = null;
        try {
            jedis = pool.getResource();
            String v = jedis.get(key);
            if (StringUtils.isNotEmpty(v)) {
                ObjectMapper mapper = new ObjectMapper();
                return mapper.readValue(v, clazz);
            }
        } catch (Exception e) {
        } finally {
            if (null != jedis) {
                jedis.close();
            }
        }
        return null;
    }
 
    /**
     * 根据key值得到String类型的返回值
     *
     * @param key key
     * @return String
     */
    public static String get(String key) {
        Jedis jedis = null;
        try {
            jedis = pool.getResource();
            String v = jedis.get(key);
            if (StringUtils.isNotEmpty(v)) {
                return v;
            }
        } catch (Exception e) {
        } finally {
            if (null != jedis) {
                jedis.close();
            }
        }
        return null;
    }
 
    public static Boolean exists(String key) {
        Jedis jedis = null;
        try {
            jedis = pool.getResource();
            return jedis.exists(key);
        } catch (Exception e) {
        } finally {
            if (null != jedis) {
                jedis.close();
            }
        }
        return null;
    }
 
    /**
     * redis的list操作:
     * 把元素插入到列表的尾部
     *
     * @param key     KEY
     * @param strings 要插入的值,变参
     * @return 返回插入后list的大小
     */
    public static Long rpush(String key, String... strings) {
        Jedis jedis = null;
        try {
            jedis = pool.getResource();
            return jedis.rpush(key, strings);
        } catch (Exception e) {
        } finally {
            if (null != jedis) {
                jedis.close();
            }
        }
        return null;
    }
 
    /**
     * redis的list操作:
     * 根据开始与结束下标取list中的值
     *
     * @param key   KEY
     * @param start 开始下标
     * @param end   结束下标
     * @return List<String>
     */
    public static List<String> lrange(String key, int start, int end) {
        Jedis jedis = null;
        try {
            jedis = pool.getResource();
            return jedis.lrange(key, start, end);
        } catch (Exception e) {
        } finally {
            if (null != jedis) {
                jedis.close();
            }
        }
        return null;
    }
 
    /**
     * redis的list操作:
     * 取列表的长度
     *
     * @param key key
     * @return Long
     */
    public static Long llen(String key) {
        Jedis jedis = null;
        try {
            jedis = pool.getResource();
            return jedis.llen(key);
        } catch (Exception e) {
        } finally {
            if (null != jedis) {
                jedis.close();
            }
        }
        return null;
    }
 
    /**
     * redis的list操作:
     * 根据值移除list中的元素
     *
     * @param key   KEY
     * @param count :
     *              count > 0 : 从表头开始向表尾搜索,移除与 value 相等的元素,数量为 count 。
     *              count < 0 : 从表尾开始向表头搜索,移除与 value 相等的元素,数量为 count 的绝对值。
     *              count = 0 : 移除表中所有与 value 相等的值。
     * @param value 要删除的值
     * @return 返回被移除的个数
     */
    public static Long lrem(String key, long count, String value) {
        Jedis jedis = null;
        try {
            jedis = pool.getResource();
            return jedis.lrem(key, count, value);
        } catch (Exception e) {
        } finally {
            if (null != jedis) {
                jedis.close();
            }
        }
        return null;
    }
 
    public static boolean setLong(String key, Long value) {
        Jedis jedis = null;
        try {
            jedis = pool.getResource();
            return "OK".equals(jedis.set(key, String.valueOf(value)));
        } catch (Exception e) {
        } finally {
            if (null != jedis) {
                jedis.close();
            }
        }
        return false;
    }
 
    public static Long getLong(String key) {
        String result = get(key);
        return result == null ? null : Long.valueOf(result);
    }
 
 
    public static Long incrBy(String key, Long increment) {
        Jedis jedis = null;
        try {
            jedis = pool.getResource();
            return jedis.incrBy(key, increment);
        } catch (Exception e) {
        } finally {
            if (null != jedis) {
                jedis.close();
            }
        }
        return null;
    }
 
    public static Long hashSet(String key, String field, String value) {
        Jedis jedis = null;
        try {
            jedis = pool.getResource();
            return jedis.hset(key, field, value);
        } catch (Exception e) {
        } finally {
            if (null != jedis) {
                jedis.close();
            }
        }
        return -1L;
    }
 
    public static Long hashSetLong(String key, String field, Long value) {
        Jedis jedis = null;
        try {
            jedis = pool.getResource();
            return jedis.hset(key, field, String.valueOf(value));
        } catch (Exception e) {
        } finally {
            if (null != jedis) {
                jedis.close();
            }
        }
        return -1L;
    }
 
    public static Long hashIncrBy(String key, String field, Long increment) {
        Jedis jedis = null;
        try {
            jedis = pool.getResource();
            return jedis.hincrBy(key, field, increment);
        } catch (Exception e) {
        } finally {
            if (null != jedis) {
                jedis.close();
            }
        }
        return -1L;
    }
 
    public static Map<String, String> hashGetAll(String key) {
        Jedis jedis = null;
        try {
            jedis = pool.getResource();
            return jedis.hgetAll(key);
        } catch (Exception e) {
        } finally {
            if (null != jedis) {
                jedis.close();
            }
        }
        return null;
    }
 
 
    public static Set<String> hashKeys(String key) {
        Jedis jedis = null;
        try {
            jedis = pool.getResource();
            return jedis.hkeys(key);
        } catch (Exception e) {
        } finally {
            if (null != jedis) {
                jedis.close();
            }
        }
        return null;
    }
 
    public static Long hashDelAll(String key, String... fields) {
        Jedis jedis = null;
        try {
            jedis = pool.getResource();
            return jedis.hdel(key, fields);
        } catch (Exception e) {
        } finally {
            if (null != jedis) {
                jedis.close();
            }
        }
        return null;
    }    

}

2.实现类中调用 package com.bcc.service;

import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.bcc.dao.usermapper; import com.bcc.pojo.City; import com.bcc.util.jedisUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service;

import java.util.List;

@Service public class userserviceimpl implements userservice{ @Autowired private usermapper um;

        //这里展示一个简单的查询方法,返回的是list集合,把list集合存入redis

@Override public List listCity(String sname) { //首先先判断redis中是否存在该key值 String aa1 = jedisUtil.get("aoo");

    if (aa1==null){  

    //若不存在首先走一下方法,从数据库中查询数据

        List<City> cities  = um.listCity(sname);

      //然后调用JSON.toJSONString()方法转为json

        String ss = JSON.toJSONString(cities);

      //存入redis

        jedisUtil.set("aoo", ss, 10000*100000);
        return cities;
    }
    else {

       //若存在,将key值查询出来,此时的key值还是json形式

        String aoo = jedisUtil.get("aoo");

       //调用JSON.parseArray()方法转为list集合

        List<City> cities = JSON.parseArray(aoo,City.class);

        //JSON.parseObject方法是转为对象

        /*City city = JSON.parseObject(aoo, City.class);*/
        return cities;
    }

}

}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。