• Jedis自己整理比较全的API


    package com.tebon.ams.utils;

    import com.alibaba.fastjson.JSON;
    import com.tebon.ams.util.ObjectUtil;
    import org.codehaus.jackson.map.ObjectMapper;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import redis.clients.jedis.Jedis;
    import redis.clients.jedis.JedisPool;
    import redis.clients.jedis.JedisPoolConfig;

    import java.io.*;
    import java.util.*;

    public class JedisUtil {

        private final static Logger logger = LoggerFactory.getLogger(JedisUtil.class);
        private static JedisPool pool;

        private JedisUtil() {
        }

        static {
            InputStream is = null;
            try {
                Properties constant = new Properties();
                is = JedisUtil.class.getClassLoader().getResourceAsStream("redis.properties");
                if (is != null) {
                    constant.load(is);
                }
                JedisPoolConfig poolConfig = new JedisPoolConfig();
                poolConfig.setMaxIdle(Integer.valueOf(constant.getProperty("redis.maxIdle", "100")));
                poolConfig.setMinIdle(Integer.valueOf(constant.getProperty("redis.minIdle", "20")));//设置最小空闲数
                poolConfig.setMaxTotal(Integer.valueOf(constant.getProperty("redis.maxTotal", "300")));
                poolConfig.setTimeBetweenEvictionRunsMillis(-1);
                poolConfig.setTestOnBorrow(true);
                String host = constant.getProperty("redis.host");
                int port = Integer.valueOf(constant.getProperty("redis.port"));
                int timeout = Integer.valueOf(constant.getProperty("redis.timeout"));
                String pwd = constant.getProperty("redis.pwd");
                int db = Integer.valueOf(constant.getProperty("redis.db", "0"));
                if (pwd == null || pwd.isEmpty()) {
                    pool = new JedisPool(poolConfig, host, port, timeout);
                } else {
                    pool = new JedisPool(poolConfig, host, port, timeout, pwd, db);
                }
            } catch (IOException e) {
                logger.error("读取redis配置文件出错", e);
            } catch (Exception e) {
                logger.error("JedisUtil init error", e);
            } finally {
                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException e) {
                        logger.error("关闭redis配置文件流出错", e);
                    }
                }
            }
        }

        public static JedisPool getJedisPool() {
            return pool;
        }

    //-----------String Start  ------------------

        /**
         * String类型的增加操作
         *
         * @param key
         * @param value
         */
        public static void set(String key, String value) {
            Jedis jedis = null;
            try {
                jedis = pool.getResource();
                jedis.set(key, value);
            } catch (Exception e) {
                logger.error("set error.", e);
                pool.returnBrokenResource(jedis);
            } finally {
                pool.returnResource(jedis);
            }
        }

        /**
         * 字符串
         *
         * @param key
         * @param value
         * @param expireTimeInSec
         */
        public static void set(String key, String value, int expireTimeInSec) {
            Jedis jedis = null;
            try {
                jedis = pool.getResource();
                jedis.setex(key, expireTimeInSec, value);
            } catch (Exception e) {
                logger.error("set ex error.", e);
                pool.returnBrokenResource(jedis);
            } finally {
                pool.returnResource(jedis);
            }
        }

        public static String get(String key) {
            Jedis jedis = null;
            String value = null;
            try {
                jedis = pool.getResource();
                value = jedis.get(key);
            } catch (Exception e) {
                logger.error("getkey error.", e);
                pool.returnBrokenResource(jedis);
            } finally {
                pool.returnResource(jedis);
            }
            return value;
        }

        /**
         * 删除某个key
         *
         * @param name
         */
        public static void del(String name) {
            Jedis jedis = null;
            try {
                jedis = pool.getResource();
                jedis.del(name);
            } catch (Exception e) {
                logger.error("pop ", e);
                pool.returnBrokenResource(jedis);
            } finally {
                pool.returnResource(jedis);
            }
        }

        /**
         * 存入对象之前进行序列化
         *
         * @param key   键
         * @param value 值
         * @return
         */
        public static String setObj(String key, Object value) {
            String result = null;
            Jedis jedis = null;
            try {
                jedis = pool.getResource();
                result = jedis.set(key.getBytes(), ObjectUtil.serialize(value));

                logger.debug("setObject {} = {}", key, value);
            } catch (Exception e) {
                logger.warn("setObject {} = {}", key, value, e);
            } finally {
                pool.returnResource(jedis);
            }
            return result;
        }

        /**
         * 设置缓存
         *
         * @param key          键
         * @param value        值
         * @param cacheSeconds 超时时间,0为不超时
         * @return
         */
        public static String setObj(String key, Object value, int cacheSeconds) {
            String result = null;
            Jedis jedis = null;
            try {
                jedis = pool.getResource();
                result = jedis.set(key.getBytes(), ObjectUtil.serialize(value));
                if (cacheSeconds != 0) {
                    jedis.expire(key, cacheSeconds);
                }
                logger.debug("setObject {} = {}", key, value);
            } catch (Exception e) {
                logger.warn("setObject {} = {}", key, value, e);
            } finally {
                pool.returnResource(jedis);
            }
            return result;
        }

        /**
         * getObj
         *
         * @param key 键
         * @return
         */
        public static Object getObj(String key) {
            Jedis jedis = null;
            try {
                jedis = pool.getResource();
                byte[] bytes = jedis.get(key.getBytes());
                if (null != bytes && bytes.length > 0) {
                    return ObjectUtil.unSerialize(bytes);
                }

                return null;
            } catch (Exception e) {
                logger.error("getobj error.", e);
                pool.returnBrokenResource(jedis);
                return null;
            } finally {
                pool.returnResource(jedis);
            }
        }

        /**
         * 删除key
         */
        public static Long delObj(String key) {
            Jedis jedis = null;
            try {
                jedis = pool.getResource();
                return jedis.del(key.getBytes());
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            } finally {
                if (jedis != null) {
                    jedis.close();
                }
            }
        }


        /**
         * 判断某个key值是否存在
         *
         * @param key
         * @return
         */
        public Boolean exists(String key) {
            Jedis jedis = null;
            Boolean flag = false;

            try {
                jedis = pool.getResource();
                flag = jedis.exists(key);
            } catch (Exception e) {
                logger.error("set error.", e);
                pool.returnBrokenResource(jedis);
            } finally {
                pool.returnResource(jedis);
            }
            return flag;
        }
    //-----------String End  ------------------
    //----------Set Start  ------------------

        /**
         * 向Set缓存中添加值
         *
         * @param key   键
         * @param value 值
         * @return
         */
        public static long setSetAdd(String key, String... value) {
            long result = 0;
            Jedis jedis = null;
            try {
                jedis = pool.getResource();
                result = jedis.sadd(key, value);
                logger.debug("setSetAdd {} = {}", key, value);
            } catch (Exception e) {
                logger.warn("setSetAdd {} = {}", key, value, e);
            } finally {
                pool.returnResource(jedis);
            }
            return result;
        }

        /**
         * 设置Set缓存
         *
         * @param key          键
         * @param value        值
         * @param cacheSeconds 超时时间,0为不超时
         * @return
         */
        public static long setSet(String key, Set<String> value, int cacheSeconds) {
            long result = 0;
            Jedis jedis = null;
            try {
                jedis = pool.getResource();
                if (jedis.exists(key)) {
                    jedis.del(key);
                }
                result = jedis.sadd(key, value.toArray(new String[value.size()]));
                if (cacheSeconds != 0) {
                    jedis.expire(key, cacheSeconds);
                }
                logger.debug("setSet {} = {}", key, value);
            } catch (Exception e) {
                logger.warn("setSet {} = {}", key, value, e);
            } finally {
                pool.returnResource(jedis);
            }
            return result;
        }

        /**
         * 获取缓存
         *
         * @param key 键
         * @return 值
         */
        public static Set<String> getSet(String key) {
            Set<String> value = null;
            Jedis jedis = null;
            try {
                jedis = pool.getResource();
                if (jedis.exists(key)) {
                    value = jedis.smembers(key);
                    logger.debug("getSet {} = {}", key, value);
                }
            } catch (Exception e) {
                logger.warn("getSet {} = {}", key, value, e);
            } finally {
                pool.returnResource(jedis);
            }
            return value;
        }

        /**
         * 设置Set缓存
         *
         * @param key          键
         * @param value        值
         * @param cacheSeconds 超时时间,0为不超时
         * @return
         */
        public static long setObjectSet(String key, Set<Object> value, int cacheSeconds) {
            long result = 0;
            Jedis jedis = null;
            try {
                jedis = pool.getResource();
                if (jedis.exists(key.getBytes())) {
                    jedis.del(key);
                }
                Set<byte[]> set = new HashSet();
                for (Object o : value) {
                    set.add(ObjectUtil.serialize(o));
                }
                result = jedis.sadd(key.getBytes(), set.toArray(new byte[set.size()][]));
                if (cacheSeconds != 0) {
                    jedis.expire(key, cacheSeconds);
                }
                logger.debug("setObjectSet {} = {}", key, value);
            } catch (Exception e) {
                logger.warn("setObjectSet {} = {}", key, value, e);
            } finally {
                pool.returnResource(jedis);
            }
            return result;
        }

        /**
         * 获取缓存
         *
         * @param key 键
         * @return 值
         */
        public static Set<Object> getObjectSet(String key) {
            Set<Object> value = null;
            Jedis jedis = null;
            try {
                jedis = pool.getResource();
                if (jedis.exists(key.getBytes())) {
                    value = new HashSet();
                    Set<byte[]> set = jedis.smembers(key.getBytes());
                    for (byte[] bs : set) {
                        value.add(ObjectUtil.unSerialize(bs));
                    }
                    logger.debug("getObjectSet {} = {}", key, value);
                }
            } catch (Exception e) {
                logger.warn("getObjectSet {} = {}", key, value, e);
            } finally {
                pool.returnResource(jedis);
            }
            return value;
        }


        /**
         * 向Set缓存中添加值
         *
         * @param key   键
         * @param value 值
         * @return
         */
        public static long setSetObjectAdd(String key, Object... value) {
            long result = 0;
            Jedis jedis = null;
            try {
                jedis = pool.getResource();
                Set<byte[]> set = new HashSet();
                for (Object o : value) {
                    //防止传数组,有null报错
                    if (o == null) {
                        continue;
                    }
                    set.add(ObjectUtil.serialize(o));

                }
                result = jedis.sadd(key.getBytes(), set.toArray(new byte[set.size()][]));
                logger.debug("setSetObjectAdd {} = {}", key, value);
            } catch (Exception e) {
                logger.warn("setSetObjectAdd {} = {}", key, value, e);
            } finally {
                pool.returnResource(jedis);
            }
            return result;
        }

        /**
         * 获取给定key中元素个数
         *
         * @param String key
         * @return 元素个数
         */
        public static long scard(String key) {
            Jedis jedis = null;
            long len = 0;
            try {
                jedis = pool.getResource();
                len = jedis.scard(key);
            } catch (Exception e) {
                logger.warn("scard {} = {}", key, e);
            } finally {
                pool.returnResource(jedis);
            }
            return len;
        }

        /**
         * 判断KEY关联的SET集合是否存在对应的成员
         *
         * @param key   Redis里面实际的KEY
         * @param value 要查找的成员
         */
        public static boolean sismember(String key, String value) {
            Jedis jedis = null;
            boolean flag = false;
            try {
                jedis = pool.getResource();
                flag = jedis.sismember(key, value);
            } catch (Exception e) {
                logger.error("set cache error.", e);
                pool.returnBrokenResource(jedis);
            } finally {
                pool.returnResource(jedis);
            }
            return flag;
        }

        /**
         * 从集合中删除指定成员
         *
         * @param key
         * @param value
         * @return
         */
        public static long srem(String key, String value) {
            Jedis jedis = null;
            long flag = 0;
            try {
                jedis = pool.getResource();
                flag = jedis.srem(key, value);
            } catch (Exception e) {
                logger.error("set cache error.", e);
                pool.returnBrokenResource(jedis);
            } finally {
                pool.returnResource(jedis);
            }
            return flag;
        }

        //-----------Set End  --------------------
    //-----------List Start-------------------
        @SuppressWarnings("unchecked")
        public static <T extends Serializable> void push(String name, T... ts) {
            Jedis jedis = null;
            try {
                jedis = pool.getResource();
                for (T t : ts)
                    jedis.lpush(name, JSON.toJSONString(t));
            } catch (Exception e) {
                logger.error("push error.", e);
                pool.returnBrokenResource(jedis);
            } finally {
                pool.returnResource(jedis);
            }
        }

        public static long lpush(String name, String json) {
            Jedis jedis = null;
            try {
                jedis = pool.getResource();
                return jedis.lpush(name, json);
            } catch (Exception e) {
                logger.error("push error.", e);
                pool.returnBrokenResource(jedis);
            } finally {
                pool.returnResource(jedis);
            }
            return -1;
        }

        public static <T extends Serializable> void push(String name, Collection<T> collection) {
            Jedis jedis = null;
            try {
                jedis = pool.getResource();
                for (T t : collection)
                    jedis.lpush(name, JSON.toJSONString(t));
            } catch (Exception e) {
                logger.error("push collection error.", e);
                pool.returnBrokenResource(jedis);
            } finally {
                pool.returnResource(jedis);
            }
        }

        /**
         * 从列表最后一位开始移除并获取列表该元素
         *
         * @param name
         * @param size
         * @param <T>
         * @return
         */
        @SuppressWarnings("unchecked")
        public static <T extends Serializable> List<T> pop(String name, int size) {
            if (size < 1) {
                return null;
            }

            Jedis jedis = null;
            List<T> list = new ArrayList<T>();
            try {
                jedis = pool.getResource();
                if (jedis.exists(name)) {
                    String value = jedis.rpop(name);
                    for (int i = 1; i <= size && value != null; i++) {
                        list.add((T) JedisUtil.str2Object(value));
                        value = jedis.rpop(name);
                    }
                }
            } catch (Exception e) {
                logger.error("pop ", e);
                pool.returnBrokenResource(jedis);
            } finally {
                pool.returnResource(jedis);
            }

            return list;
        }

        @SuppressWarnings("unchecked")
        public static <T extends Serializable> List<T> lrange(String name, int start, int end) {
            Jedis jedis = null;
            List<T> list = new ArrayList<T>();
            try {
                jedis = pool.getResource();
                if (jedis.exists(name)) {
                    List<String> strList = jedis.lrange(name, start, end);
                    int size = strList == null ? 0 : strList.size();
                    for (int i = 0; i < size; i++) {
                        list.add((T) JedisUtil.str2Object(strList.get(i)));
                    }
                }
            } catch (Exception e) {
                logger.error("lrange ", e);
                pool.returnBrokenResource(jedis);
            } finally {
                pool.returnResource(jedis);
            }

            return list;
        }

        public static <T extends Serializable> List<T> lrange(String name, int start, int end, Class<T> classes) {
            Jedis jedis = null;
            List<T> list = new ArrayList<T>();
            try {
                jedis = pool.getResource();
                if (jedis.exists(name)) {
                    List<String> strList = jedis.lrange(name, start, end);
                    int size = strList == null ? 0 : strList.size();
                    ObjectMapper objectMapper = new ObjectMapper();
                    for (int i = 0; i < size; i++) {
                        list.add(objectMapper.readValue(strList.get(i), classes));
                    }
                }
            } catch (Exception e) {
                logger.error("lrange ", e);
                pool.returnBrokenResource(jedis);
            } finally {
                pool.returnResource(jedis);
            }

            return list;
        }

        public static long length(String name) {
            Jedis jedis = null;
            long length = 0;
            try {
                jedis = pool.getResource();
                length = jedis.llen(name);
            } catch (Exception e) {
                logger.error("pop ", e);
                pool.returnBrokenResource(jedis);
            } finally {
                pool.returnResource(jedis);
            }

            return length;
        }

        /**
         * 移除列表中的元素
         *
         * @param name
         * @param count count > 0 : 从表头开始向表尾搜索,移除与 VALUE 相等的元素,数量为 COUNT 。
         *              count < 0 : 从表尾开始向表头搜索,移除与 VALUE 相等的元素,数量为 COUNT 的绝对值。
         *              count = 0 : 移除表中所有与 VALUE 相等的值。
         */
        public static void lrem(String name, int count, String value) {
            Jedis jedis = null;
            try {
                jedis = pool.getResource();
                jedis.lrem(name, count, JSON.toJSONString(value));
            } catch (Exception e) {
                logger.error("pop ", e);
                pool.returnBrokenResource(jedis);
            } finally {
                pool.returnResource(jedis);
            }
        }
    //---------------List End----------------
    //--------------ZSet Start---------------

        /**
         * 向有序不重复集合添加数据
         *
         * @param key
         * @param score
         * @param member
         * @return
         */
        public static long zadd(String key, double score, String member) {
            Jedis jedis = null;
            try {
                jedis = pool.getResource();
                return jedis.zadd(key, score, member);
            } catch (Exception e) {
                logger.error("zadd ", e);
                pool.returnBrokenResource(jedis);
            } finally {
                pool.returnResource(jedis);
            }
            return 0;
        }

        public static long zadd(String key, Map<String, Double> scoreMembers) {
            Jedis jedis = null;
            try {
                jedis = pool.getResource();
                return jedis.zadd(key, scoreMembers);
            } catch (Exception e) {
                logger.error("zadd ", e);
                pool.returnBrokenResource(jedis);
            } finally {
                pool.returnResource(jedis);
            }
            return 0;
        }

        /**
         * 移除有序集合中给定的字典区间的所有成员
         *
         * @param key
         * @param start
         * @param end
         * @return
         */
        public static long zremrangeByRank(String key, long start, long end) {
            Jedis jedis = null;
            try {
                jedis = pool.getResource();
                return jedis.zremrangeByRank(key, start, end);
            } catch (Exception e) {
                logger.error("zremrangeByRank ", e);
                pool.returnBrokenResource(jedis);
            } finally {
                pool.returnResource(jedis);
            }
            return 0;
        }

        /**
         * 通过索引区间返回有序集合成指定区间内的成员
         *
         * @param key
         * @param start
         * @param end
         * @return
         */
        public static Set<String> zrange(String key, long start, long end) {
            Jedis jedis = null;
            try {
                jedis = pool.getResource();
                return jedis.zrange(key, start, end);
            } catch (Exception e) {
                logger.error("zrang ", e);
                pool.returnBrokenResource(jedis);
            } finally {
                pool.returnResource(jedis);
            }
            return null;
        }

        /**
         * 获取有序集合的成员数
         *
         * @param key
         * @return
         */
        public static long zcard(String key) {
            Jedis jedis = null;
            try {
                jedis = pool.getResource();
                return jedis.zcard(key);
            } catch (Exception e) {
                logger.error("zcard ", e);
                pool.returnBrokenResource(jedis);
            } finally {
                pool.returnResource(jedis);
            }
            return 0;
        }
    //--------------End ZSet-----------------------
    //--------------Start Hash---------------------

        /**
         * 将哈希表 key 中的字段 field 的值设为 value
         *
         * @param key
         * @param field
         * @param value
         * @return
         */
        public static long hset(String key, String field, String value) {
            Jedis jedis = null;
            try {
                jedis = pool.getResource();
                return jedis.hset(key, field, value);
            } catch (Exception e) {
                logger.error("hset ", e);
                pool.returnBrokenResource(jedis);
            } finally {
                pool.returnResource(jedis);
            }
            return 0;
        }

        /**
         * 获取所有给定字段的值
         *
         * @param key
         * @param field
         * @return
         */
        public static String hget(String key, String field) {
            Jedis jedis = null;
            try {
                jedis = pool.getResource();
                return jedis.hget(key, field);
            } catch (Exception e) {
                logger.error("hget ", e);
                pool.returnBrokenResource(jedis);
            } finally {
                pool.returnResource(jedis);
            }
            return null;
        }

        /**
         * 删除一个或多个哈希表字段
         *
         * @param key
         * @param field
         * @return
         */
        public static Long hdel(String key, String field) {
            Jedis jedis = null;
            try {
                jedis = pool.getResource();
                return jedis.hdel(key, field);
            } catch (Exception e) {
                logger.error("hget ", e);
                pool.returnBrokenResource(jedis);
            } finally {
                pool.returnResource(jedis);
            }
            return null;
        }

        /**
         * 获取byte[]类型Key
         *
         * @param key
         * @return /*
         */
      /*  public static byte[] getBytesKey(Object object) {
            if (object instanceof String) {
                return StringUtils.getBytes((String) object);
            } else {
                return ObjectUtil.serialize(object);
            }
        }*/
        public static Object str2Object(String str) throws Exception {

            ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(getByte(str)));
            return ois.readObject();
        }

        public static byte[] getByte(String str) {
            byte[] bt = null;
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            try {
                if (str != null) {
                    ObjectOutputStream objos = new ObjectOutputStream(baos);
                    objos.writeObject(str);
                    bt = baos.toByteArray();
                }
            } catch (Exception e) {
                bt = (byte[]) null;
                e.printStackTrace();
            }
            return bt;
        }

    }

  • 相关阅读:
    Java中try-catch-finally的一点理解
    子类继承父类的私有属性
    Java中的String[] args
    Java类和类成员的访问权限修饰符
    JAVA中抽象类与接口的区别
    Java C# .net 和 C C++ 跨平台的区别
    Java中的instanceof关键字
    深入理解JAVA的多态性[转]
    Linux文件系统的目录结构
    硬盘分区
  • 原文地址:https://www.cnblogs.com/muliu/p/9414053.html
Copyright © 2020-2023  润新知