Redis超实用工具类

概述

Redis(全称:Remote Dictionary Server 远程字典服务)是一个开源的使用ANSI C语言编写、支持网络、可基于内存亦可持久化的日志型、Key-Value数据库、并提供多种语言的API。日常开发中会经常使用到该数据库,在这里记录一下常用到的方法。

相关代码

Maven配置

<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
 </dependency>

初始化

/**
*Redis配置类
*/
@Component
public class DataConfig {

    @Value("${redis.ip}")
    String ip;
    
    @Value("${redis.port}")
    int port;
    
    @Value("${redis.password}")
    String password;
    
    @PostConstruct
    public void init() {
        if(StringUtils.isNotEmpty(password)) {
            RedisUtils.init(ip, port, password);
        }else {
            RedisUtils.init(ip, port);
        }
    }
}

初始化配置操作

public class RedisUtils {
    private static JedisPool pool;

    public static JedisPool getPool() {
        return pool;
    }
    //用于判断当前Redis连接是否已经初始化
    public static boolean isInit;
    // 最大空闲连接数
    private static final int MAX_IDLE_COUNT = 500;
    // 最大连接数
    private static final int MAX_TOTAL_COUNT = 300;
    // 获取连接时的最大等待毫秒数(如果设置为阻塞时BlockWhenExhausted),如果超时就抛异常, 小于零:阻塞不确定的时间, 默认-1
    private static final int MAX_WAIT_MILLIS = 5000;
    // 默认数据过期时间
    public static final int DEFAULT_EXPIRE_SECONDS = 2 * 24 * 60 * 60;
    //不过期的时间
    public static final int FOREVER_EXPIRE_SECONDS = -1;

    public static void init(String ip, int port) {
        init(ip, port, null, MAX_IDLE_COUNT, MAX_TOTAL_COUNT, MAX_WAIT_MILLIS);
    }

    public static void init(String ip, int port, String password) {
        init(ip, port, password, MAX_IDLE_COUNT, MAX_TOTAL_COUNT, MAX_WAIT_MILLIS);
    }

    public static void init(String ip, int port, String password, int maxIdleCount, int maxTotalCount,
            int maxWaitMillis) {
        if (isInit) {
            return;
        }
        isInit = true;
        // 建立连接池配置参数
        JedisPoolConfig config = new JedisPoolConfig();
        // 最大空闲连接数
        config.setMaxIdle(maxIdleCount);
        // 设置最大阻塞时间,记住是毫秒数milliseconds
        config.setMaxWaitMillis(maxWaitMillis);
        // 最大连接数, 默认8个
        config.setMaxTotal(maxTotalCount);
        // 创建连接池
        if (org.apache.commons.lang3.StringUtils.isEmpty(password)) {
            pool = new JedisPool(config, ip, port);
        } else {
            pool = new JedisPool(config, ip, port, 5000, password);
        }
    }

    /**
     * 释放资源
     * @param jedis
     */
    private static void closeResource(Jedis jedis) {
        try {
            jedis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Key值的常用操作,放在RedisUtils类中

    /**
     * 是否存在指定的key
     * @param key
     * @return
     */
    public static boolean existsKey(String key) {
        Jedis jedis = pool.getResource();
        try {
            return jedis.exists(key);
        } catch (Exception e) {
            jedis.close();
            e.printStackTrace();
        } finally {
            closeResource(jedis);
        }
    }

    /**
     * key表达式,如:brand_*
     * @param keyExpression
     * @return
     */
    public static Set<String> getKeys(String keyExpression) {
        Jedis jedis = pool.getResource();
        try {
            return jedis.keys(keyExpression);
        } catch (Exception e) {
            jedis.close();
            e.printStackTrace();
            return Sets.newHashSet();
        } finally {
            closeResource(jedis);
        }
    }

    /**
     * 移除指定的key
     * @param key
     */
    public static void delKey(String key) {
        Jedis jedis = pool.getResource();
        try {
            jedis.del(key);
        } catch (Exception e) {
            jedis.close();
            Logger.error(e.getMessage(), e);
        } finally {
            closeResource(jedis);
        }
    }

    /**
     * 单独设置指定key的过期时间
     * @param key-key
     * @param expireSeconds--过期时间(秒)
     */
    public static void setKeyExpireTime(String key, int expireSeconds) {
        if (expireSeconds <= 0) {
            return;
        }
        Jedis jedis = pool.getResource();
        try {
            jedis.expire(key, expireSeconds);
        } catch (Exception e) {
            jedis.close();
            Logger.error(e.getMessage(), e);
        } finally {
            closeResource(jedis);
        }
    }

Incr 命令

Redis Incr 命令将 key 中储存的数字值增一。
如果 key 不存在,那么 key 的值会先被初始化为 0 ,然后再执行 INCR 操作。
如果值包含错误的类型,或字符串类型的值不能表示为数字,那么返回一个错误。
本操作的值限制在 64 位(bit)有符号数字表示之内。

    /**
     * 获取自增id
     * 
     * @param key-key
     * @return
     */
    public static int getAutoIncreaseId(String key) {
        Jedis jedis = pool.getResource();
        try {
            return jedis.incr(key).intValue();
        } catch (Exception e) {
            Logger.error(e.getMessage(), e);
            return -1;
        } finally {
            closeResource(jedis);
        }
    }

    /**
     * 将key中储存的数字值增1
     * @param key -key
     * @return
     */
    public static long incr(String key, int expireSeconds) {
        Jedis jedis = pool.getResource();
        try {
            // 当 key 不存在时,返回 -2 。
            // 当 key 存在但没有设置剩余生存时间时,返回 -1 。
            // 否则,以毫秒为单位,返回 key 的剩余生存时间。
            long ttl = jedis.ttl(key);
            if (ttl > 0) {
                return jedis.incr(key);
            } else if (ttl < 0) {
                Long incr = jedis.incr(key);
                jedis.expire(key, expireSeconds);
                return incr;
            }
            return -1;
        } catch (Exception e) {
            Logger.error(e.getMessage(), e);
            return -1;
        } finally {
            closeResource(jedis);
        }
    }

    /**
     * 将key中储存的数字值增1
     * @param key -key
     * @return
     */
    public static long incr(String key) {
        Jedis jedis = pool.getResource();
        try {
            Long incr = jedis.incr(key);
            return incr;
        } catch (Exception e) {
            Logger.error(e.getMessage(), e);
            return -1;
        } finally {
            closeResource(jedis);
        }
    }

     /**
     * 自减操作
     */
    public static int getAutoDecrement(String key) {
        Jedis jedis = pool.getResource();
        try {
            return jedis.decr(key).intValue();
        } catch (Exception e) {
            // Logger.error(e.getMessage(), e);
            e.printStackTrace();
            return -1;
        } finally {
            closeResource(jedis);
        }
    }

根据Key查询/写入值或对象

    /**
     * 从缓存获取指定key的对象
     * 
     * @param key
     * @param c
     * @return
     */
    public static <T> T getValue(String key, Class<T> c) {
        String s = getValue(key);
        if (StringUtils.isEmpty(s)) {
            return null;
        }
        return gson.fromJson(s, c);
    }

    /**
     * 从缓存批量获取keys的对象集合
     * @param keys
     * @param c
     * @param <T>
     * @return
     */
    public static <T> List<T> getValues(String[] keys, Class<T> c) {
        Jedis jedis = pool.getResource();
        List<T> list = new ArrayList<T>();
        try {
            List<String> results = jedis.mget(keys);
            for (String s : results) {
                if (!StringUtils.isEmpty(s)) {
                    list.add(JSONObject.parseObject(s, c));
                }
            }
        } catch (Exception e) {
            jedis.close();
            e.printStackTrace();
        } finally {
            closeResource(jedis);
        }
        return list;
    }

    /**
     * 从缓存取得指定key的字符串<br/>
     * 该方法不对外提供,以免与T参数方法误用
     * 
     * @param key
     * @return
     */
    private static String getValue(String key) {
        Jedis jedis = pool.getResource();
        try {
            String s = jedis.get(key);
            return s == null ? "" : s;
        } catch (Exception e) {
            jedis.close();
            e.printStackTrace();
            return "";
        } finally {
            closeResource(jedis);
        }
    }

    /**
     * 保存单个对象(如果对象已经存在,则覆盖)<br/>
     * 默认过期时间:3天
     * 
     * @param key
     * @param value
     */
    public static <T> void setValue(String key, T value) {
        setValue(key, value, DEFAULT_EXPIRE_SECONDS);
    }

    /**
     * 保存单个对象(如果对象已经存在,则覆盖)<br/>
     * 
     * @param key
     * @param value
     * @param expireSeconds-过期时间(秒)
     */
    public static <T> void setValue(String key, T value, int expireSeconds) {
        if (value != null) {
            setValue(key, value, expireSeconds, false);
        }
    }

    /**
     * 保存单个对象(如果对象已经存在,则覆盖)-包括flag
     * @param key
     * @param value
     * @param expireSeconds
     * @param needSetFlag
     * @param <T>
     */
    public static <T> void setValue(String key, T value, int expireSeconds, boolean needSetFlag) {
        if (value != null) {
            setValue(key, JSONObject.toJSONString(value), expireSeconds, needSetFlag);
            // setValue(key, gson.toJson(value), expireSeconds, needSetFlag);
        }
    }

    /**
     * 保存字符串(如果对象已经存在,则覆盖)
     * 
     * @param key-key
     * @param value-value
     * @param expireTime-过期时间,类型:yyyy-MM-dd
     *            HH:mm:ss
     */
    public static <T> void setValue(String key, T value, String expireTime) {
        if (value != null) {
            long toTime = FastDateUtils.getTime(expireTime, FastDateFormat.DATE_TIME);
            int expireSeconds = (int) (toTime - System.currentTimeMillis()) / 1000;
            if (expireSeconds > 0) {
                setValue(key, value, expireSeconds);
            }
        }
    }

    /**
     * 保存字符串(如果对象已经存在,则覆盖)
     * @param key
     * @param value
     * @param expireSeconds
     * @param needSetFlag
     */
    private static void setValue(String key, String value, int expireSeconds, boolean needSetFlag) {
        Jedis jedis = pool.getResource();
        try {
            if (expireSeconds > 0) {
                jedis.set(key, value);
                jedis.expire(key, expireSeconds);
            } else {// 不设置过期时间则需检测之前是否设置有过期时间,有则需设置回原有的过期时间
                // 获取key过期时间,因为set后原有的key过期时间将被清空
                long expireTime = jedis.pttl(key);// 剩余过期毫秒数
                jedis.set(key, value);
                if (expireTime > 0) {
                    int time = (int) Math.ceil((float) expireTime / 1000);
                    jedis.expire(key, time);// 再设置原有剩余秒数 向上取整,如2.1 则为3
                }
            }
        } catch (Exception e) {
            jedis.close();
            e.printStackTrace();
            throw new RedisException(e.getMessage(), e);
        } finally {
            closeResource(jedis);
        }
    }

setnx命令操作

将 key 的值设为 value ,当且仅当 key 不存在。
若给定的 key 已经存在,则 SETNX 不做任何动作。
SETNX 是『SET if Not eXists』(如果不存在,则 SET)的简写。

/**
     * 保存对象(如果不存在key的话)
     * 
     * @param key
     * @param value
     * @return 不存在key,则保存成功,返回true,存在key,则保存失败,返回false
     */
    public static <T> boolean setnxWithNoExpire(String key, T value) {
        return setnx(key, value, 0);
    }

    /**
     * 保存对象(如果不存在key的话)
     * 
     * @param key
     * @param value
     * @return 不存在key,则保存成功,返回true,存在key,则保存失败,返回false
     */
    public static <T> boolean setnx(String key, T value, int expireSeconds) {
        return setnx(key, JSONObject.toJSONString(value), expireSeconds);
    }

    /**
     * 保存字符串(如果不存在key的话)
     * 
     * @param key
     * @param value
     * @return 不存在key,则保存成功,返回true,存在key,则保存失败,返回false
     */
    private static boolean setnx(String key, String value, int expireSeconds) {
        Jedis jedis = pool.getResource();
        try {
            // 1 if the key was set 0 if the key was not set
            boolean setnxOK = jedis.setnx(key, value) == 1;

            // 设置过期时间
            if (expireSeconds > 0) {
                if (setnxOK) { // 设置成功了,则设置失效时间
                    jedis.expire(key, expireSeconds);
                } else if (!setnxOK && jedis.pttl(key) < 0) {// 或者由于某些异常状态setnx执行成功
                    // 但expire没有成功,可能会导致锁永远释放不掉,这里强制设置过期时间
                    jedis.expire(key, expireSeconds);
                }
            }
            if (setnxOK) {
                return true;
            }
        } catch (Exception e) {
            jedis.close();
            e.printStackTrace();
        } finally {
            closeResource(jedis);
        }
        return false;
    }

List操作

/**
     * 设置一个全新的list<br/>
     * 如果之前已经存在key,则会先移除,再添加
     * 
     * @param key
     * @param list
     */
    public static <T> void setList(String key, List<T> list) {
        if (list == null || list.size() == 0) {
            return;
        }
        Jedis jedis = pool.getResource();
        try {
            String[] ss = new String[list.size()];
            for (int i = 0; i < list.size(); i++) {
                ss[i] = JSONObject.toJSONString(list.get(i));
            }
            delKey(key);// 先移除之前的key,再新增
            jedis.rpush(key, ss);
        } catch (Exception e) {
            jedis.close();
            e.printStackTrace();
            throw new RedisException(e.getMessage(), e);
        } finally {
            closeResource(jedis);
        }
    }

    /**
     *
     * @param key
     * @param list
     * @param timeOut
     * @param <T>
     */
    public static <T> void setList(String key, List<T> list,Integer timeOut) {
        if (list == null || list.size() == 0) {
            return;
        }
        Jedis jedis = pool.getResource();
        try {
            String[] ss = new String[list.size()];
            for (int i = 0; i < list.size(); i++) {
                ss[i] = JSONObject.toJSONString(list.get(i));
            }
            jedis.rpush(key, ss);
            jedis.expire(key,timeOut);
        } catch (Exception e) {
            jedis.close();
            e.printStackTrace();
            throw new RedisException(e.getMessage(), e);
        } finally {
            closeResource(jedis);
        }
    }

    /**
     * 添加一个value到原有列表到尾部
     * @param key
     * @param value
     * @param <T>
     */
    public static <T> void addList(String key, T value) {
        Jedis jedis = pool.getResource();
        try {
            String[] ss = new String[1];
            ss[0] = JSONObject.toJSONString(value);
            jedis.rpush(key, ss);
        } catch (Exception e) {
            jedis.close();
            e.printStackTrace();
            throw new RedisException(e.getMessage(), e);
        } finally {
            closeResource(jedis);
        }
    }

    /**
     * 添加一个value到原有列表头部
     * 
     * @param key
     * @param value
     */
    public static <T> void addListToHead(String key, T value) {
        Jedis jedis = pool.getResource();
        try {
            String[] ss = new String[1];
            ss[0] = JSONObject.toJSONString(value);
            jedis.lpush(key, JSONObject.toJSONString(value));
        } catch (Exception e) {
            jedis.close();
            e.printStackTrace();
            throw new RedisException(e.getMessage(), e);
        } finally {
            closeResource(jedis);
        }
    }

    /**
     * 设置list中指定索引的值
     * 
     * @param key
     * @param index-索引
     * @param value
     */
    public static <T> void setListElement(String key, int index, T value) {
        Jedis jedis = pool.getResource();
        try {
            jedis.lset(key, index, JSONObject.toJSONString(value));
        } catch (Exception e) {
            jedis.close();
            e.printStackTrace();
            throw new RedisException(e.getMessage(), e);
        } finally {
            closeResource(jedis);
        }
    }

    /**
     * 返回某个范围内的集合,无结果集则返回空list
     * 
     * @param key
     * @param start-起始索引(包含,从0开始)
     * @param end-结束索引(包含)
     * @return
     */
    private static List<String> getListRange(String key, int start, int end) {
        Jedis jedis = pool.getResource();
        try {
            return jedis.lrange(key, start, end);
        } catch (Exception e) {
            jedis.close();
            e.printStackTrace();
            return null;
        } finally {
            closeResource(jedis);
        }
    }

    /**
     * 返回某个范围内的集合,无结果集则返回空list
     * 
     * @param key
     * @param start-起始索引(包含,从0开始)
     * @param end-结束索引(包含)
     * @param c-具体类
     * @return
     */
    public static <T> List<T> getListRange(String key, int start, int end, Class<T> c) {
        List<String> slist = getListRange(key, start, end);
        List<T> list = new ArrayList<T>();
        for (String s : slist) {
            list.add(gson.fromJson(s, c));
        }
        return list.isEmpty() ? null : list;
    }

    /**
     * 分页获取list
     * 
     * @param key
     * @param pageNow-当前页数
     * @param pageSize-每页记录数
     * @param c
     * @return
     */
    public static <T> List<T> getListPage(String key, int pageNow, int pageSize, Class<T> c) {
        int startIndex = (pageNow - 1) * pageSize;
        int endIndex = pageNow * pageSize - 1;
        return getListRange(key, startIndex, endIndex, c);
    }

    /**
     * 获取指定key下的列表所有记录
     * 
     * @param key
     * @param c
     * @return
     */
    public static <T> List<T> getAllList(String key, Class<T> c) {
        return getListRange(key, 0, -1, c);
    }

    /**
     * 获取列表第一个元素
     * 
     * @param key
     * @param c
     * @return
     */
    public static <T> T getListFirstElement(String key, Class<T> c) {
        Jedis jedis = pool.getResource();
        try {
            return JSONObject.parseObject(jedis.lindex(key, 0), c);
        } catch (Exception e) {
            jedis.close();
            e.printStackTrace();
            return null;
        } finally {
            closeResource(jedis);
        }
    }

    /**
     * 返回并删除list中的首元素
     * 
     * @param key
     * @return
     */
    public static <T> T getListPop(String key, Class<T> c) {
        Jedis jedis = pool.getResource();
        try {
            return JSONObject.parseObject(jedis.lpop(key), c);
        } catch (Exception e) {
            jedis.close();
            e.printStackTrace();
            return null;
        } finally {
            closeResource(jedis);
        }
    }

    /**
     * 获取列表最后一个元素
     * 
     * @param key
     * @param c
     * @return
     */
    public static <T> T getListLastElement(String key, Class<T> c) {
        Jedis jedis = pool.getResource();
        try {
            return JSONObject.parseObject(jedis.lindex(key, -1), c);
        } catch (Exception e) {
            jedis.close();
            e.printStackTrace();
            return null;
        } finally {
            closeResource(jedis);
        }
    }

    /**
     * 返回list的集合个数
     * 
     * @param key
     * @return
     */
    public static int getListSize(String key) {
        Jedis jedis = pool.getResource();
        try {
            return jedis.llen(key).intValue();
        } catch (Exception e) {
            jedis.close();
            e.printStackTrace();
            return 0;
        } finally {
            closeResource(jedis);
        }
    }

    /**
     * 删除list的指定对象
     * 
     * @param key
     * @param values
     */
    @SuppressWarnings("unchecked")
    public static <T> void removeValueFromList(String key, T... values) {
        Jedis jedis = pool.getResource();
        try {
            for (T v : values) {
                jedis.lrem(key, 0, JSONObject.toJSONString(v));
            }
        } catch (Exception e) {
            jedis.close();
            e.printStackTrace();
            throw new RedisException(e.getMessage(), e);
        } finally {
            closeResource(jedis);
        }
    }

    /**
     * 删除一个列表
     * 
     * @param key
     */
    public static void removeList(String key) {
        Jedis jedis = pool.getResource();
        try {
            if (jedis.llen(key) > 0) {
                jedis.ltrim(key, 1, 0);
            }
        } catch (Exception e) {
            jedis.close();
            e.printStackTrace();
            throw new RedisException(e.getMessage(), e);
        } finally {
            closeResource(jedis);
        }
    }

Map操作

/**
     * 保存Java map to Redis map
     *  @param hashKey
     * @param map
     */
    public static <T> void addToHashMap(String hashKey, Map<String, T> map) {
        if (map == null || map.isEmpty()) {
            return;
        }
        Jedis jedis = pool.getResource();
        try {
            for (String key : map.keySet()) {
                String value = JSONObject.toJSONString(map.get(key));
                jedis.hset(hashKey, key, value);
            }
            jedis.expire(hashKey, DEFAULT_EXPIRE_SECONDS);
        } catch (Exception e) {
            jedis.close();
            e.printStackTrace();
            throw new RedisException(e.getMessage(), e);
        } finally {
            closeResource(jedis);
        }
    }

    /**
     * 保存Java map to Redis map
     * 
     * @param hashKey
     * @param map
     */
    public static <K, V> void addToHashMap2(String hashKey, Map<K, V> map) {
        if (map == null || map.isEmpty()) {
            return;
        }
        Jedis jedis = pool.getResource();
        try {
            for (K key : map.keySet()) {
                String value = JSONObject.toJSONString(map.get(key));
                jedis.hset(hashKey, String.valueOf(key), value);
            }
        } catch (Exception e) {
            jedis.close();
            e.printStackTrace();
            throw new RedisException(e.getMessage(), e);
        } finally {
            closeResource(jedis);
        }
    }

    /**
     * 保存Java value to Redis map
     * 
     * @param hashKey
     * @param key
     * @param value
     */
    public static <T> void addToHashMap(String hashKey, String key, T value) {
        Jedis jedis = pool.getResource();
        try {
            jedis.hset(hashKey, key, JSONObject.toJSONString(value));
        } catch (Exception e) {
            jedis.close();
            e.printStackTrace();
            throw new RedisException(e.getMessage(), e);
        } finally {
            closeResource(jedis);
        }
    }

    /**
     * 从hashmap中返回某个key的值
     * 
     * @param hashKey
     * @param key
     * @param c-类型
     * @return
     */
    public static <T> T getValueFromHashMap(String hashKey, String key, Class<T> c) {
        Jedis jedis = pool.getResource();
        try {
            String s = jedis.hget(hashKey, key);
            if (StringUtils.isEmpty(s)) {
                return null;
            }
            return JSONObject.parseObject(s, c);
        } catch (Exception e) {
            jedis.close();
            e.printStackTrace();
            return null;
        } finally {
            closeResource(jedis);
        }
    }

    /**
     * 从hashmap中返回某个key的值
     * @param hashKey
     * @param key
     * @param typeOfT
     * @param <T>
     * @return
     */
    public static <T> T getValueFromHashMap(String hashKey, String key, Type typeOfT) {
        Jedis jedis = pool.getResource();
        try {
            String s = jedis.hget(hashKey, key);
            if (StringUtils.isEmpty(s)) {
                return null;
            }
            return JSONObject.parseObject(s, typeOfT);
        } catch (Exception e) {
            jedis.close();
            e.printStackTrace();
            return null;
        } finally {
            closeResource(jedis);
        }
    }

    /**
     * 返回整个map对象
     * 
     * @param hashKey
     * @return
     */
    public static <T> Map<String, T> getAllFromHashMap(String hashKey, Class<T> c) {
        Jedis jedis = pool.getResource();
        try {
            Map<String, String> map = jedis.hgetAll(hashKey);
            Map<String, T> tMap = new HashMap<String, T>(map.size());
            for (String key : map.keySet()) {
                T value = JSONObject.parseObject(map.get(key), c);
                tMap.put(key, value);
            }
            return tMap;
        } catch (Exception e) {
            jedis.close();
            e.printStackTrace();
            return null;
        } finally {
            closeResource(jedis);
        }
    }

    /**
     * 获取hashmap的size
     * 
     * @param hashKey
     * @return
     */
    public static long getSizeFromHashMap(String hashKey) {
        Jedis jedis = pool.getResource();
        try {
            return jedis.hlen(hashKey);
        } catch (Exception e) {
            jedis.close();
            e.printStackTrace();
            return 0;
        } finally {
            closeResource(jedis);
        }
    }

    /**
     * 删除map中的指定key
     * 
     * @param hashKey
     * @param keys
     */
    public static void removeFromHashMap(String hashKey, String... keys) {
        Jedis jedis = pool.getResource();
        try {
            jedis.hdel(hashKey, keys);
        } catch (Exception e) {
            jedis.close();
            e.printStackTrace();
        } finally {
            closeResource(jedis);
        }
    }

    /**
     * 获取某个Map的所有key集合
     * 
     * @param hashKey
     * @return
     */
    public static Set<String> getKeysFromHashMap(String hashKey) {
        Jedis jedis = pool.getResource();
        try {
            return jedis.hkeys(hashKey);
        } catch (Exception e) {
            jedis.close();
            e.printStackTrace();
            return null;
        } finally {
            closeResource(jedis);
        }
    }

    /**
     * 删除某Map所有的元素
     * 
     * @param hashKey
     */
    public static void removeHashMap(String hashKey) {
        if (StringUtils.isEmpty(hashKey)) {
            return;
        }
        Set<String> keySet = getKeysFromHashMap(hashKey);
        if (keySet == null || keySet.isEmpty()) {
            return;
        }
        // 化成数组
        String[] keyArr = keySet.toArray(new String[] {});
        if (keyArr == null || keyArr.length == 0) {
            return;
        }
        // 批量删除
        removeFromHashMap(hashKey, keyArr);
    }

    /**
     * 在hashmap中是否存在指定的key
     * @param hashKey
     * @param key
     * @return
     */
    public static boolean hasKeyFromHashMap(String hashKey, String key) {
        Jedis jedis = pool.getResource();
        try {
            return jedis.hexists(hashKey, key);
        } catch (Exception e) {
            jedis.close();
            e.printStackTrace();
            return false;
        } finally {
            closeResource(jedis);
        }
    }

zSet操作

Redis 有序集合和集合一样也是string类型元素的集合,且不允许重复的成员。
不同的是每个元素都会关联一个double类型的分数。redis正是通过分数来为集合中的成员进行从小到大的排序。
有序集合的成员是唯一的,但分数(score)却可以重复。
集合是通过哈希表实现的,所以添加,删除,查找的复杂度都是O(1)。 集合中最大的成员数为 232 - 1 (4294967295, 每个集合可存储40多亿个成员)。

    /**
     * 写入zset队列
     * @param key
     * @param map
     * @return
     */
    public static boolean setZsetValue(String key, Map<String, Double> map) {
        if (StringUtils.isEmpty(key)) {
            return false;
        }
        if(map == null || map.size() <= 0) {
            return false;
        }
        Jedis jedis = pool.getResource();
        try {
            Long count = jedis.zadd(key, map);
            if(count > 0) {
                return true;
            }
        } catch (Exception e) {
            closeResource(jedis);
            Logger.error("RedisClient->setZsetValue插入队列失败  map=[" + JSONObject.toJSONString(map) + "]", e);
        } finally {
            closeResource(jedis);
        }
        return false;
    }

    /**
     * 根据范围返回zSet队列任务
     * @param key
     * @param minIndex
     * @param maxIndex
     * @return
     */
    public static Set<String> getZsetValuesByRange(String key, int minIndex, int maxIndex) {
        Set<String> set = Collections.emptySet();
        if(existsKey(key)) {
            if(getZsetCount(key) <= 0) {
                return set;
            }
            Jedis jedis = pool.getResource();
            try {
                set = jedis.zrange(key, minIndex, maxIndex);
                return set;
            } catch (Exception e) {
                closeResource(jedis);
                Logger.error("RedisClient->getZsetValuesByRange获取队列任务失败   key=[" + key + "], index=["+minIndex+","+maxIndex+"]", e);
            } finally {
                closeResource(jedis);
            }
        }
        return set;
    }

    /**
     * 根据Value删除指定Zset队列元素
     * @param key
     * @param value
     * @return
     */
    public static boolean remZsetValue(String key, String value) {
        if (StringUtils.isEmpty(key)) {
            return false;
        }
        if(existsKey(key)) {
            Jedis jedis = pool.getResource();
            try {
                Long count = jedis.zrem(key, value);
                if(count > 0) {
                    return true;
                }
            } catch (Exception e) {
                closeResource(jedis);
                Logger.error("RedisClient->remZsetValue删除队列任务失败 key=[" + key + "], value=["+value+"]", e);
                return false;
            } finally {
                closeResource(jedis);
            }
        }
        return false;
    }

    public static long getZsetCount(String key) {
        if (StringUtils.isEmpty(key)) {
            return 0;
        }
        if(existsKey(key)) {
            Jedis jedis = pool.getResource();
            try {
                return jedis.zcard(key);
            } catch (Exception e) {
                closeResource(jedis);
                e.printStackTrace();
                return 0;
            } finally {
                closeResource(jedis);
            }
        }
        return 0;
    }

Redis Hincrby 命令

Redis Hincrby 命令用于为哈希表中的字段值加上指定增量值。
增量也可以为负数,相当于对指定字段进行减法操作。
如果哈希表的 key 不存在,一个新的哈希表被创建并执行 HINCRBY 命令。
如果指定的字段不存在,那么在执行命令前,字段的值被初始化为 0 。
对一个储存字符串值的字段执行 HINCRBY 命令将造成一个错误。
本操作的值被限制在 64 位(bit)有符号数字表示之内。

/**
     * 为哈希表 key 中的域 field 的值加1
     * @param key
     * @param field
     * @return
     */
    public static long incrementHashMapValue(String key, String field) {
        return incrementHashMapValue(key, field, 1);
    }

    /**
     * 为哈希表 key 中的域 field 的值减1
     * @param key
     * @param field
     * @return
     */
    public static long decrementHashMapValue(String key, String field) {
        return incrementHashMapValue(key, field, -1);
    }

    public static long incrementHashMapValue(String key, String field, long increment) {
        Jedis jedis = pool.getResource();
        try {
            return jedis.hincrBy(key, field, increment);
        } catch (Exception e) {
            // Logger.error(e.getMessage(), e);
            e.printStackTrace();
            return -1;
        } finally {
            closeResource(jedis);
        }
    }

Set集合(无序列表)操作

/**
     * 添加set集合
     */
    public static void addSetValue(String key, String value, int expireSeconds) {
        Jedis jedis = pool.getResource();
        try {
            if (expireSeconds > 0) {
                jedis.sadd(key, value);
                jedis.expire(key, expireSeconds);
            } else {// 不设置过期时间则需检测之前是否设置有过期时间,有则需设置回原有的过期时间
                // 获取key过期时间,因为set后原有的key过期时间将被清空
                long expireTime = jedis.pttl(key);// 剩余过期毫秒数
                jedis.sadd(key, value);
                if (expireTime > 0) {
                    int time = (int) Math.ceil((float) expireTime / 1000);
                    jedis.expire(key, time);// 再设置原有剩余秒数 向上取整,如2.1 则为3
                }
            }
        } catch (Exception e) {
            jedis.close();
            e.printStackTrace();
            throw new RedisException(e.getMessage(), e);
        } finally {
            closeResource(jedis);
        }
    }

    /**
     * 批量-添加set集合
     */
    public static void addSetValue(String key, String[] value, int expireSeconds) {
        Jedis jedis = pool.getResource();
        try {
            if (expireSeconds > 0) {
                jedis.sadd(key, value);
                jedis.expire(key, expireSeconds);
            } else {// 不设置过期时间则需检测之前是否设置有过期时间,有则需设置回原有的过期时间
                // 获取key过期时间,因为set后原有的key过期时间将被清空
                long expireTime = jedis.pttl(key);// 剩余过期毫秒数
                jedis.sadd(key, value);
                if (expireTime > 0) {
                    int time = (int) Math.ceil((float) expireTime / 1000);
                    jedis.expire(key, time);// 再设置原有剩余秒数 向上取整,如2.1 则为3
                }
            }
        } catch (Exception e) {
            jedis.close();
            e.printStackTrace();
            throw new RedisException(e.getMessage(), e);
        } finally {
            closeResource(jedis);
        }
    }

    /**
     * 移除集合中一个或多个成员
     * @param key
     * @param members
     * @return
     */
    public static boolean delSetValues(String key, String... members){
        Jedis jedis = null;
        try {
            jedis = pool.getResource();
            Long value = jedis.srem(key, members);
            if(value > 0){
                return true;
            }
        }catch (Exception e) {
            e.printStackTrace();
        }finally{
            if(jedis != null){
                jedis.close();
            }
        }
        return false;
    }

    /**
     * 获取set集合
     */
    public static Set<String> getSetValue(String key) {
        Jedis jedis = pool.getResource();
        try {
            return jedis.smembers(key);
        } catch (Exception e) {
            jedis.close();
            e.printStackTrace();
            return Sets.newHashSet();
        } finally {
            closeResource(jedis);
        }
    }

    /**
     * 获取对象转换的Set集合
     * @param key
     * @param c
     * @param <T>
     * @return
     */
    public static <T> Set<T> getSetValue(String key, Class<T> c) {
        Set<String> set = getSetValue(key);
        Set<T> temp = new HashSet<>();
        if(set.size() > 0){
            for (String s : set) {
                temp.add(JSONObject.parseObject(s, c));
            }
        }
        return temp;
    }

    /**
     * 弹出Set集合
     * @param sourceKey
     * @param targetKey
     * @return
     */
    public static Set<String> moveSetValue(String sourceKey, String targetKey){
        Jedis jedis = pool.getResource();
        try {
            //获取当前列表元素
            Set<String> currentSet = jedis.smembers(sourceKey);
            if(currentSet.size() <= 0){
                return Sets.newHashSet();
            }
            //将元素移到另外一个集合
            for (String value :currentSet){
                jedis.smove(sourceKey, targetKey, value);
            }
            Set<String> set = jedis.smembers(targetKey);
            return set;
        } catch (Exception e) {
            jedis.close();
            e.printStackTrace();
            return Sets.newHashSet();
        } finally {
            closeResource(jedis);
        }
    }

    /**
     * 弹出Set对象集合
     * @param sourceKey
     * @param targetKey
     * @param c
     * @param <T>
     * @return
     */
    public static <T> Set<T> moveSetValue(String sourceKey, String targetKey, Class<T> c) {
        Set<String> set = moveSetValue(sourceKey, targetKey);
        Set<T> temp = new HashSet<>();
        if(set.size() > 0){
            for (String s : set) {
                temp.add(JSONObject.parseObject(s, c));
            }
        }
        return temp;
    }

    /**
     * 获取Set集合总数
     * @param key
     * @return
     */
    public static long getSetCount(String key) {
        Jedis jedis = pool.getResource();
        try {
            return jedis.scard(key);
        } catch (Exception e) {
            jedis.close();
            e.printStackTrace();
            return BasicDataUtil.DEFAULT_LONG;
        } finally {
            closeResource(jedis);
        }
    }

    /**
     * 查询set集合内是否存在该元素
     * @param key
     * @param val
     * @return
     */
    public static Boolean existsKeyInSet(String key, String val) {
        Jedis jedis = pool.getResource();
        try {
            return jedis.sismember(key, val);
        } catch (Exception e) {
            jedis.close();
            e.printStackTrace();
            return Boolean.FALSE;
        } finally {
            closeResource(jedis);
        }
    }

/**
     * 从set集合中弹出一定数量的元素(数量由传入参数控制)
     */
    public static Set<String> getSetValueBySpop(String key, long count){
        Jedis jedis = pool.getResource();
        Set<String> value;
        try {
            value = jedis.spop(key,count);
        }catch (Exception e) {
            jedis.close();
            e.printStackTrace();
            return new HashSet<>();
        } finally {
            closeResource(jedis);
        }
        return value;
    }

Redis提供的API函数十分丰富,能帮助我们解决系统中很多性能问题。后续会提供一些用到Redis的技术方案。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,185评论 6 503
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,652评论 3 393
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,524评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,339评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,387评论 6 391
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,287评论 1 301
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,130评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,985评论 0 275
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,420评论 1 313
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,617评论 3 334
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,779评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,477评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,088评论 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,716评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,857评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,876评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,700评论 2 354

推荐阅读更多精彩内容