RedisTemplate工具类1

 

本文参考:https://blog.it-follower.com/posts/2563248908.html

SpringBoot项目集成Redis相当简单,只需要pom中加入对应依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>


yml中,配置好spring.redis.host,spring.redis.port即可。

具体如何封装,直接上代码。

/**
 * Redis工具类,使用之前请确保RedisTemplate成功注入
 *
 * @author ye17186
 * @version 2019/2/22 10:48
 */
public class RedisUtils {
 
    private RedisUtils() {
    }
 
    @SuppressWarnings("unchecked")
    private static RedisTemplate<String, Object> redisTemplate = SpringUtils
        .getBean("redisTemplate", RedisTemplate.class);
 
    /**
     * 设置有效时间
     *
     * @param key Redis键
     * @param timeout 超时时间
     * @return true=设置成功;false=设置失败
     */
    public static boolean expire(final String key, final long timeout) {
 
        return expire(key, timeout, TimeUnit.SECONDS);
    }
 
    /**
     * 设置有效时间
     *
     * @param key Redis键
     * @param timeout 超时时间
     * @param unit 时间单位
     * @return true=设置成功;false=设置失败
     */
    public static boolean expire(final String key, final long timeout, final TimeUnit unit) {
 
        Boolean ret = redisTemplate.expire(key, timeout, unit);
        return ret != null && ret;
    }
 
    /**
     * 删除单个key
     *
     * @param key 键
     * @return true=删除成功;false=删除失败
     */
    public static boolean del(final String key) {
 
        Boolean ret = redisTemplate.delete(key);
        return ret != null && ret;
    }
 
    /**
     * 删除多个key
     *
     * @param keys 键集合
     * @return 成功删除的个数
     */
    public static long del(final Collection<String> keys) {
 
        Long ret = redisTemplate.delete(keys);
        return ret == null ? 0 : ret;
    }
 
    /**
     * 存入普通对象
     *
     * @param key Redis键
     * @param value 值
     */
    public static void set(final String key, final Object value) {
 
        redisTemplate.opsForValue().set(key, value, 1, TimeUnit.MINUTES);
    }
 
    // 存储普通对象操作
 
    /**
     * 存入普通对象
     *
     * @param key 键
     * @param value 值
     * @param timeout 有效期,单位秒
     */
    public static void set(final String key, final Object value, final long timeout) {
 
        redisTemplate.opsForValue().set(key, value, timeout, TimeUnit.SECONDS);
    }
 
    /**
     * 获取普通对象
     *
     * @param key 键
     * @return 对象
     */
    public static Object get(final String key) {
 
        return redisTemplate.opsForValue().get(key);
    }
 
    // 存储Hash操作
 
    /**
     * 往Hash中存入数据
     *
     * @param key Redis键
     * @param hKey Hash键
     * @param value 值
     */
    public static void hPut(final String key, final String hKey, final Object value) {
 
        redisTemplate.opsForHash().put(key, hKey, value);
    }
 
    /**
     * 往Hash中存入多个数据
     *
     * @param key Redis键
     * @param values Hash键值对
     */
    public static void hPutAll(final String key, final Map<String, Object> values) {
 
        redisTemplate.opsForHash().putAll(key, values);
    }
 
    /**
     * 获取Hash中的数据
     *
     * @param key Redis键
     * @param hKey Hash键
     * @return Hash中的对象
     */
    public static Object hGet(final String key, final String hKey) {
 
        return redisTemplate.opsForHash().get(key, hKey);
    }
 
    /**
     * 获取多个Hash中的数据
     *
     * @param key Redis键
     * @param hKeys Hash键集合
     * @return Hash对象集合
     */
    public static List<Object> hMultiGet(final String key, final Collection<Object> hKeys) {
 
        return redisTemplate.opsForHash().multiGet(key, hKeys);
    }
 
    // 存储Set相关操作
 
    /**
     * 往Set中存入数据
     *
     * @param key Redis键
     * @param values 值
     * @return 存入的个数
     */
    public static long sSet(final String key, final Object... values) {
        Long count = redisTemplate.opsForSet().add(key, values);
        return count == null ? 0 : count;
    }
 
    /**
     * 删除Set中的数据
     *
     * @param key Redis键
     * @param values 值
     * @return 移除的个数
     */
    public static long sDel(final String key, final Object... values) {
        Long count = redisTemplate.opsForSet().remove(key, values);
        return count == null ? 0 : count;
    }
 
    // 存储List相关操作
 
    /**
     * 往List中存入数据
     *
     * @param key Redis键
     * @param value 数据
     * @return 存入的个数
     */
    public static long lPush(final String key, final Object value) {
        Long count = redisTemplate.opsForList().rightPush(key, value);
        return count == null ? 0 : count;
    }
 
    /**
     * 往List中存入多个数据
     *
     * @param key Redis键
     * @param values 多个数据
     * @return 存入的个数
     */
    public static long lPushAll(final String key, final Collection<Object> values) {
        Long count = redisTemplate.opsForList().rightPushAll(key, values);
        return count == null ? 0 : count;
    }
 
    /**
     * 往List中存入多个数据
     *
     * @param key Redis键
     * @param values 多个数据
     * @return 存入的个数
     */
    public static long lPushAll(final String key, final Object... values) {
        Long count = redisTemplate.opsForList().rightPushAll(key, values);
        return count == null ? 0 : count;
    }
 
    /**
     * 从List中获取begin到end之间的元素
     *
     * @param key Redis键
     * @param start 开始位置
     * @param end 结束位置(start=0,end=-1表示获取全部元素)
     * @return List对象
     */
    public static List<Object> lGet(final String key, final int start, final int end) {
        return redisTemplate.opsForList().range(key, start, end);
    }
}

 

RedisTemplate工具类2

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

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

@Component
public final class RedisUtil {

    @Autowired
    private RedisTemplate redisTemplate;

    // =============================common============================

    public Set<String> keys(String pattern) {
        return redisTemplate.keys(pattern);
    }

    /**
     * 指定缓存失效时间
     *
     * @param key  键
     * @param time 时间(秒)
     * @return
     */
    public boolean expire(String key, long time) {
        try {
            if (time > 0) {
                redisTemplate.expire(key, time, TimeUnit.SECONDS);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 根据key 获取过期时间
     *
     * @param key 键 不能为null
     * @return 时间(秒) 返回0代表为永久有效
     */
    public long getExpire(String key) {
        return redisTemplate.getExpire(key, TimeUnit.SECONDS);
    }

    /**
     * 判断key是否存在
     *
     * @param key 键
     * @return true 存在 false不存在
     */
    public boolean hasKey(String key) {
        try {
            return redisTemplate.hasKey(key);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 删除缓存
     *
     * @param key 可以传一个值 或多个
     */
    @SuppressWarnings("unchecked")
    public void del(String... key) {
        if (key != null && key.length > 0) {
            if (key.length == 1) {
                redisTemplate.delete(key[0]);
            } else {
                redisTemplate.delete(CollectionUtils.arrayToList(key));
            }
        }
    }

    // ============================String=============================

    /**
     * 普通缓存获取
     *
     * @param key 键
     * @return 值
     */
    public <T> T get(String key) {
        if (key == null) return null;
        ValueOperations<String, T> operation = redisTemplate.opsForValue();
        return operation.get(key);
    }

    /**
     * 普通缓存放入
     *
     * @param key   键
     * @param value 值
     * @return true成功 false失败
     */
    public boolean set(String key, Object value) {
        try {
            redisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }

    /**
     * 普通缓存放入并设置时间
     *
     * @param key   键
     * @param value 值
     * @param time  时间(秒) time要大于0 如果time小于等于0 将设置无限期
     * @return true成功 false 失败
     */
    public boolean set(String key, Object value, long time) {
        try {
            if (time > 0) {
                redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
            } else {
                set(key, value);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 递增
     *
     * @param key   键
     * @param delta 要增加几(大于0)
     * @return
     */
    public long incr(String key, long delta) {
        if (delta < 0) {
            throw new RuntimeException("递增因子必须大于0");
        }
        return redisTemplate.opsForValue().increment(key, delta);
    }

    /**
     * 递减
     *
     * @param key   键
     * @param delta 要减少几(小于0)
     * @return
     */
    public long decr(String key, long delta) {
        if (delta < 0) {
            throw new RuntimeException("递减因子必须大于0");
        }
        return redisTemplate.opsForValue().increment(key, -delta);
    }

    // ================================Map=================================

    /**
     * HashGet
     *
     * @param key  键 不能为null
     * @param item 项 不能为null
     * @return 值
     */
    public Object hget(String key, String item) {
        return redisTemplate.opsForHash().get(key, item);
    }

    /**
     * 获取hashKey对应的所有键值
     *
     * @param key 键
     * @return 对应的多个键值
     */
    public Map<Object, Object> hmget(String key) {
        return redisTemplate.opsForHash().entries(key);
    }

    /**
     * HashSet
     *
     * @param key 键
     * @param map 对应多个键值
     * @return true 成功 false 失败
     */
    public boolean hmset(String key, Map<String, Object> map) {
        try {
            redisTemplate.opsForHash().putAll(key, map);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * HashSet 并设置时间
     *
     * @param key  键
     * @param map  对应多个键值
     * @param time 时间(秒)
     * @return true成功 false失败
     */
    public boolean hmset(String key, Map<String, Object> map, long time) {
        try {
            redisTemplate.opsForHash().putAll(key, map);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 向一张hash表中放入数据,如果不存在将创建
     *
     * @param key   键
     * @param item  项
     * @param value 值
     * @return true 成功 false失败
     */
    public boolean hset(String key, String item, Object value) {
        try {
            redisTemplate.opsForHash().put(key, item, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 向一张hash表中放入数据,如果不存在将创建
     *
     * @param key   键
     * @param item  项
     * @param value 值
     * @param time  时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
     * @return true 成功 false失败
     */
    public boolean hset(String key, String item, Object value, long time) {
        try {
            redisTemplate.opsForHash().put(key, item, value);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 删除hash表中的值
     *
     * @param key  键 不能为null
     * @param item 项 可以使多个 不能为null
     */
    public void hdel(String key, Object... item) {
        redisTemplate.opsForHash().delete(key, item);
    }

    /**
     * 判断hash表中是否有该项的值
     *
     * @param key  键 不能为null
     * @param item 项 不能为null
     * @return true 存在 false不存在
     */
    public boolean hHasKey(String key, String item) {
        return redisTemplate.opsForHash().hasKey(key, item);
    }

    /**
     * hash递增 如果不存在,就会创建一个 并把新增后的值返回
     *
     * @param key  键
     * @param item 项
     * @param by   要增加几(大于0)
     * @return
     */
    public double hincr(String key, String item, double by) {
        return redisTemplate.opsForHash().increment(key, item, by);
    }

    /**
     * hash递减
     *
     * @param key  键
     * @param item 项
     * @param by   要减少记(小于0)
     * @return
     */
    public double hdecr(String key, String item, double by) {
        return redisTemplate.opsForHash().increment(key, item, -by);
    }

    // ============================set=============================

    /**
     * 根据key获取Set中的所有值
     *
     * @param key 键
     * @return
     */
    public Set<Object> sGet(String key) {
        try {
            return redisTemplate.opsForSet().members(key);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 根据value从一个set中查询,是否存在
     *
     * @param key   键
     * @param value 值
     * @return true 存在 false不存在
     */
    public boolean sHasKey(String key, Object value) {
        try {
            return redisTemplate.opsForSet().isMember(key, value);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 将数据放入set缓存
     *
     * @param key    键
     * @param values 值 可以是多个
     * @return 成功个数
     */
    public long sSet(String key, Object... values) {
        try {
            return redisTemplate.opsForSet().add(key, values);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 将set数据放入缓存
     *
     * @param key    键
     * @param time   时间(秒)
     * @param values 值 可以是多个
     * @return 成功个数
     */
    public long sSetAndTime(String key, long time, Object... values) {
        try {
            Long count = redisTemplate.opsForSet().add(key, values);
            if (time > 0)
                expire(key, time);
            return count;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 获取set缓存的长度
     *
     * @param key 键
     * @return
     */
    public long sGetSetSize(String key) {
        try {
            return redisTemplate.opsForSet().size(key);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 移除值为value的
     *
     * @param key    键
     * @param values 值 可以是多个
     * @return 移除的个数
     */
    public long setRemove(String key, Object... values) {
        try {
            Long count = redisTemplate.opsForSet().remove(key, values);
            return count;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
    // ===============================list=================================

    /**
     * 获取list缓存的内容
     *
     * @param key   键
     * @param start 开始
     * @param end   结束 0 到 -1代表所有值
     * @return
     */
    public List<Object> lGet(String key, long start, long end) {
        try {
            return redisTemplate.opsForList().range(key, start, end);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取list缓存的长度
     *
     * @param key 键
     * @return
     */
    public long lGetListSize(String key) {
        try {
            return redisTemplate.opsForList().size(key);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 通过索引 获取list中的值
     *
     * @param key   键
     * @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
     * @return
     */
    public Object lGetIndex(String key, long index) {
        try {
            return redisTemplate.opsForList().index(key, index);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 将list放入缓存
     *
     * @param key   键
     * @param value 值
     * @param time  时间(秒)
     * @return
     */
    public boolean lSet(String key, Object value) {
        try {
            redisTemplate.opsForList().rightPush(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 将list放入缓存
     *
     * @param key   键
     * @param value 值
     * @param time  时间(秒)
     * @return
     */
    public boolean lSet(String key, Object value, long time) {
        try {
            redisTemplate.opsForList().rightPush(key, value);
            if (time > 0)
                expire(key, time);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 将list放入缓存
     *
     * @param key   键
     * @param value 值
     * @param time  时间(秒)
     * @return
     */
    public boolean lSet(String key, List<Object> value) {
        try {
            redisTemplate.opsForList().rightPushAll(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 将list放入缓存
     *
     * @param key   键
     * @param value 值
     * @param time  时间(秒)
     * @return
     */
    public boolean lSet(String key, List<Object> value, long time) {
        try {
            redisTemplate.opsForList().rightPushAll(key, value);
            if (time > 0)
                expire(key, time);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 根据索引修改list中的某条数据
     *
     * @param key   键
     * @param index 索引
     * @param value 值
     * @return
     */
    public boolean lUpdateIndex(String key, long index, Object value) {
        try {
            redisTemplate.opsForList().set(key, index, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 移除N个值为value
     *
     * @param key   键
     * @param count 移除多少个
     * @param value 值
     * @return 移除的个数
     */
    public long lRemove(String key, long count, Object value) {
        try {
            return redisTemplate.opsForList().remove(key, count, value);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
}

 

 

基于jedis的redis工具类

以下为部分代码,完整的代码和redis应用实例,请移步到码云。

码云地址:  https://gitee.com/JYFlyer/spring-boot-redis-case

/**
 * 基于jedis的redis操作工具类
 * @author jyf
 * @time 2019/8/3 22:30
 */
public final class RedisUtils {
 
   /*
    除了该工具类提供的方法外,还可以在外面调用getJedis()方法,获取到jedis实例后,调用它原生的api来操作
     */
 
    /**
     * 获取jedis对象,并选择redis库。jedis默认是0号库,可传入1-16之间的数选择库存放数据
     * 原则上使用一个redis库存放数据,通过特定的key的命令规则来区分不同的数据就行了。
     *
     * @param index redis库号。使用可变参数的目的就是该参数可传可不传。
     * @return 返回jedis对象
     */
    public static Jedis getJedis(int... index) {
        Jedis jedis = MyJedisPoolConfig.getJedisPool().getResource();
        if (index != null && index.length > 0) {
            if (index[0] > 0 && index[0] <= 16){
                jedis.select(index[0]);
            }
        }
        return jedis;
    }
 
    /*########################  key的操作  ################################*/
 
    /**
     * 根据pattern返回当前库中的key
     *
     * @param pattern
     * @return
     */
    public static Set<String> keys(String pattern) {
        Jedis jedis = null;
        Set<String> keys = null;
        try {
            jedis = getJedis();
            keys = jedis.keys(pattern);
        }finally {
            if (jedis != null){
                jedis.close();
            }
        }
        return keys;
    }
 
    /**
     * 删除一个或多个key
     *
     * @param key 一个或多个key
     */
    public static Long del(String... key) {
        Jedis jedis = null;
        Long delNum = 0L;
        try {
            jedis = getJedis();
            delNum =jedis.del(key);
        }finally {
            if (jedis != null){
                jedis.close();
            }
        }
        return delNum;
    }
 
    /**
     * 批量删除
     * @param keyList 要删除的key的集合
     */
    public static void mdel(List<String> keyList){
        Jedis jedis = getJedis();
        //获取pipeline
        Pipeline pipeline = jedis.pipelined();
        for (String key : keyList) {
            pipeline.del(key);
        }
        //执行结果同步,这样才能保证结果的正确性。实际上不执行该方法也执行了上面的命令,但是结果确不一定完全正确。
        //注意
        pipeline.sync();
        //关闭连接
        jedis.close();
    }
 
    /**
     * 判断某个key是否还存在
     *
     * @param key key
     * @return
     */
    public static Boolean exists(String key) {
        Jedis jedis = null;
        Boolean flag = false;
        try {
            jedis = getJedis();
            flag = jedis.exists(key);
        }finally {
            if (jedis != null){
                jedis.close();
            }
        }
        return flag;
    }
 
    /**
     * 设置某个key的过期时间,单位秒
     *
     * @param key key
     * @param seconds 过期时间秒
     */
    public static void expire(String key, int seconds) {
        Jedis jedis = null;
        try {
            jedis = getJedis();
            jedis.expire(key, seconds);
        }finally {
            if (jedis != null){
                jedis.close();
            }
        }
    }
 
    /**
     * 查看某个key还有几秒过期,-1表示永不过期 ,-2表示已过期
     *
     * @param key key
     * @return
     */
    public static Long timeToLive(String key) {
        Jedis jedis = null;
        Long ttl;
        try {
            jedis = getJedis();
            ttl = jedis.ttl(key);
        }finally {
            if (jedis != null){
                jedis.close();
            }
        }
        return ttl;
    }
 
    /**
     * 查看某个key对应的value的类型
     *
     * @param key
     * @return
     */
    public static String type(String key) {
        Jedis jedis = null;
        String type = null;
        try {
            jedis = getJedis();
            type = jedis.type(key);
        }finally {
            if (jedis != null){
                jedis.close();
            }
        }
        return type;
    }
 
 
    /*########################  string(字符串)的操作  ####################*/
 
    /**
     * 获取某个key的value,类型要对,只能value是string的才能获取
     *
     * @param key
     * @return
     */
    public static String get(String key) {
        Jedis jedis = null;
        String value = null;
        try {
            jedis = getJedis();
            value = jedis.get(key);
        }finally {
            if (jedis != null){
                jedis.close();
            }
        }
        return value;
    }
 
    /**
     * 设置某个key的value
     *
     * @param key
     * @param value
     */
    public static void set(String key, String value) {
        Jedis jedis = null;
        try {
            jedis = getJedis();
            jedis.set(key, value);
        }finally {
            if (jedis != null){
                jedis.close();
            }
        }
    }
 
    /**
     * 字符串后追加内容
     *
     * @param key key
     * @param appendContent 要追加的内容
     */
    public static void append(String key, String appendContent) {
        Jedis jedis = null;
        try {
            jedis = getJedis();
            jedis.append(key, appendContent);
        }finally {
            if (jedis != null){
                jedis.close();
            }
        }
    }
 
    /**
     * 返回key的value的长度
     *
     * @param key
     * @return
     */
    public static Long strlen(String key) {
        Jedis jedis = null;
        Long strLen = 0L;
        try {
            jedis = getJedis();
            strLen = jedis.strlen(key);
        }finally {
            if (jedis != null){
                jedis.close();
            }
        }
        return strLen;
    }
 
    /**
     * value 加1 必
     * 须是字符型数字
     * @param key
     * @return 增加后的值
     */
    public static Long incr(String key) {
        Jedis jedis = null;
        Long incrResult = 0L;
        try {
            jedis = getJedis();
            incrResult = jedis.incr(key);
        }finally {
            if (jedis != null){
                jedis.close();
            }
        }
        return incrResult;
    }
 
    /**
     * value 减1   必须是字符型数字
     *
     * @param key
     * @return
     */
    public static Long decr(String key) {
        Jedis jedis = null;
        Long decrResult = 0L;
        try {
            jedis = getJedis();
            decrResult = jedis.decr(key);
        }finally {
            if (jedis != null){
                jedis.close();
            }
        }
        return decrResult;
    }
 
    /**
     * value 加increment
     *
     * @param key key
     * @param increment 加几
     * @return
     */
    public static Long incrby(String key, int increment) {
        Jedis jedis = null;
        Long incrByResult = 0L;
        try {
            jedis = getJedis();
            incrByResult = jedis.incrBy(key, increment);
        }finally {
            if (jedis != null){
                jedis.close();
            }
        }
        return incrByResult;
    }
 
    /**
     * value 减increment
     *
     * @param key
     * @param increment
     * @return
     */
    public static Long decrby(String key, int increment) {
        Jedis jedis = null;
        Long decrByResult = 0L;
        try {
            jedis = getJedis();
            decrByResult = jedis.decrBy(key, increment);
        }finally {
            if (jedis != null){
                jedis.close();
            }
        }
        return decrByResult;
    }
 
    /**
     * 给某个key设置过期时间和value,成功返回OK
     *
     * @param key key
     * @param seconds 过期时间秒
     * @param value 设置的值
     * @return
     */
    public static String setex(String key, int seconds, String value) {
        Jedis jedis = null;
        String result = null;
        try {
            jedis = getJedis();
            result = jedis.setex(key, seconds, value);
        }finally {
            if (jedis != null){
                jedis.close();
            }
        }
        return result;
    }
 
 
    /*########################  list(列表)的操作  #######################*/
    //lpush rpush lpop rpop lrange lindex llen lset
 
    /**
     * 从左边向列表中添加值
     *
     * @param key key
     * @param str 要添加的值
     */
    public static void lpush(String key, String str) {
        Jedis jedis = null;
        try {
            jedis = getJedis();
            jedis.lpush(key, str);
        }finally {
            if (jedis != null){
                jedis.close();
            }
        }
    }
 
    /**
     * 从右边向列表中添加值
     *
     * @param key key
     * @param str 要添加的值
     */
    public static void rpush(String key, String str) {
        Jedis jedis = null;
        try {
            jedis = getJedis();
            jedis.rpush(key, str);
        }finally {
            if (jedis != null){
                jedis.close();
            }
        }
    }
 
    /**
     * 从左边取出一个列表中的值
     *
     * @param key
     * @return
     */
    public static String lpop(String key) {
        Jedis jedis = null;
        String lpop = null;
        try {
            jedis = getJedis();
            lpop = jedis.lpop(key);
        }finally {
            if (jedis != null){
                jedis.close();
            }
        }
        return lpop;
    }
 
    /**
     * 从右边取出一个列表中的值
     *
     * @param key
     * @return
     */
    public static String rpop(String key) {
        Jedis jedis = null;
        String rpop = null;
        try {
            jedis = getJedis();
            rpop = jedis.rpop(key);
        }finally {
            if (jedis != null){
                jedis.close();
            }
        }
        return rpop;
    }
 
    /**
     * 取出列表中指定范围内的值,0 到 -1 表示全部
     *
     * @param key
     * @param startIndex
     * @param endIndex
     * @return
     */
    public static List<String> lrange(String key, int startIndex, int endIndex) {
        Jedis jedis = null;
        List<String> result = null;
        try {
            jedis = getJedis();
            result = jedis.lrange(key, startIndex, endIndex);
        }finally {
            if (jedis != null){
                jedis.close();
            }
        }
        return result;
    }
 
    /**
     * 返回某列表指定索引位置的值
     *
     * @param key 列表key
     * @param index 索引位置
     * @return
     */
    public static String lindex(String key, int index) {
        Jedis jedis = null;
        String lindex = null;
        try {
            jedis = getJedis();
            lindex = jedis.lindex(key, index);
        }finally {
            if (jedis != null){
                jedis.close();
            }
        }
        return lindex;
    }
 
    /**
     * 返回某列表的长度
     *
     * @param key
     * @return
     */
    public static Long llen(String key) {
        Jedis jedis = null;
        Long llen = 0L;
        try {
            jedis = getJedis();
            llen = jedis.llen(key);
        }finally {
            if (jedis != null){
                jedis.close();
            }
        }
        return llen;
    }
 
    /**
     * 给某列表指定位置设置为指定的值
     *
     * @param key
     * @param index
     * @param str
     */
    public static void lset(String key, Long index, String str) {
        Jedis jedis = null;
        try {
            jedis = getJedis();
            jedis.lset(key, index, str);
        }finally {
            if (jedis != null){
                jedis.close();
            }
        }
    }
 
    /**
     * 对列表进行剪裁,保留指定闭区间的元素(索引位置也会重排)
     * @param key 列表key
     * @param startIndex 开始索引位置
     * @param endIndex 结束索引位置
     */
    public static void ltrim(String key,Integer startIndex,Integer endIndex){
        Jedis jedis = null;
        try {
            jedis = getJedis();
            jedis.ltrim(key, startIndex, endIndex);
        }finally {
            if (jedis != null){
                jedis.close();
            }
        }
    }
 
    /**
     * 从列表的左边阻塞弹出一个元素
     * @param key 列表的key
     * @param timeout 阻塞超时时间,0表示若没有元素就永久阻塞
     * @return
     */
    public static List<String> blpop(String key,Integer timeout){
        Jedis jedis = null;
        List<String> valueList = null;
        try {
            jedis = getJedis();
            valueList = jedis.blpop(timeout, key);
        }finally {
            if (jedis != null){
                jedis.close();
            }
        }
        return valueList;
    }
 
    /**
     * 从列表的右边阻塞弹出一个元素
     * @param key 列表的key
     * @param timeout 阻塞超时时间,0表示若没有元素就永久阻塞
     * @return
     */
    public static List<String> brpop(String key,Integer timeout){
        Jedis jedis = null;
        List<String> valueList = null;
        try {
            jedis = getJedis();
            valueList = jedis.brpop(timeout, key);
        }finally {
            if (jedis != null){
                jedis.close();
            }
        }
        return valueList;
    }
 
 
    /*########################  hash(哈希表)的操作  #######################*/
    //hset hget hmset hmget hgetall hdel hkeys hvals hexists hincrby
 
    /**
     * 给某个hash表设置一个键值对
     *
     * @param key
     * @param field
     * @param value
     */
    public static void hset(String key, String field, String value) {
        Jedis jedis = null;
        try {
            jedis = getJedis();
            jedis.hset(key, field, value);
        }finally {
            if (jedis != null){
                jedis.close();
            }
        }
    }
 
    /**
     * 取出某个hash表中某个field对应的value
     *
     * @param key key
     * @param field field
     * @return
     */
    public static String hget(String key, String field) {
        Jedis jedis = null;
        String hget = null;
        try {
            jedis = getJedis();
            hget = jedis.hget(key, field);
        }finally {
            if (jedis != null){
                jedis.close();
            }
        }
        return hget;
    }
 
    /**
     * 某个hash表设置一个或多个键值对
     *
     * @param key
     * @param kvMap
     */
    public static void hmset(String key, Map<String, String> kvMap) {
        Jedis jedis = null;
        try {
            jedis = getJedis();
            jedis.hmset(key, kvMap);
        }finally {
            if (jedis != null){
                jedis.close();
            }
        }
    }
 
    /**
     * 取出某个hash表中任意多个key对应的value的集合
     *
     * @param key
     * @param fields
     * @return
     */
    public static List<String> hmget(String key, String... fields) {
        Jedis jedis = null;
        List<String> hmget = null;
        try {
            jedis = getJedis();
            hmget = jedis.hmget(key, fields);
        }finally {
            if (jedis != null){
                jedis.close();
            }
        }
        return hmget;
    }
 
    /**
     * 取出某个hash表中所有的键值对
     *
     * @param key
     * @return
     */
    public static Map<String, String> hgetall(String key) {
        Jedis jedis = null;
        Map<String, String> kvMap = null;
        try {
            jedis = getJedis();
            kvMap = jedis.hgetAll(key);
        }finally {
            if (jedis != null){
                jedis.close();
            }
        }
        return kvMap;
    }
 
    /**
     * 判断某个hash表中的某个key是否存在
     *
     * @param key
     * @param field
     * @return
     */
    public static Boolean hexists(String key, String field) {
        Jedis jedis = null;
        Boolean exists = null;
        try {
            jedis = getJedis();
            exists = jedis.hexists(key, field);
        }finally {
            if (jedis != null){
                jedis.close();
            }
        }
        return exists;
    }
 
    /**
     * 返回某个hash表中所有的key
     *
     * @param key
     * @return
     */
    public static Set<String> hkeys(String key) {
        Jedis jedis = null;
        Set<String> keys = null;
        try {
            jedis = getJedis();
            keys = jedis.hkeys(key);
        }finally {
            if (jedis != null){
                jedis.close();
            }
        }
        return keys;
    }
 
    /**
     * 返回某个hash表中所有的value
     *
     * @param key
     * @return
     */
    public static List<String> hvals(String key) {
        Jedis jedis = null;
        List<String> hvals = null;
        try {
            jedis = getJedis();
            hvals = jedis.hvals(key);
        }finally {
            if (jedis != null){
                jedis.close();
            }
        }
        return hvals;
    }
 
    /**
     * 删除某个hash表中的一个或多个键值对
     *
     * @param key
     * @param fields
     */
    public static void hdel(String key, String... fields) {
        Jedis jedis = null;
        try {
            jedis = getJedis();
            jedis.hdel(key, fields);
        }finally {
            if (jedis != null){
                jedis.close();
            }
        }
    }
 
    /**
     * 给某个hash表中的某个field的value增加多少
     *
     * @param key       hash表的key
     * @param field     表中的某个field
     * @param increment 增加多少
     * @return
     */
    public static Long hincrby(String key, String field, Long increment) {
        Jedis jedis = null;
        Long result = null;
        try {
            jedis = getJedis();
            result = jedis.hincrBy(key, field, increment);
        }finally {
            if (jedis != null){
                jedis.close();
            }
        }
        return result;
    }
 
    /*########################  set(集合)的操作  ###########################*/
 
    /**
     * 往set集合中添加一个或多个元素
     * @param key key
     * @param members 要添加的元素
     * @return 添加成功的元素个数
     */
    public static Long sadd(String key,String... members){
        Jedis jedis = null;
        Long num = 0L;
        try {
            jedis = getJedis();
            num = jedis.sadd(key, members);
        }finally {
            if (jedis != null){
                jedis.close();
            }
        }
        return num;
    }
 
    /**
     * 返回set集合中的所有元素,顺序与加入时的顺序一致
     * @param key key
     * @return
     */
    public static Set<String> smembers(String key){
        Jedis jedis = null;
        Set<String> members = null;
        try {
            jedis = getJedis();
            members = jedis.smembers(key);
        }finally {
            if (jedis != null){
                jedis.close();
            }
        }
        return members;
    }
 
    /**
     * 判断集合中是否存在某个元素
     * @param key key
     * @param member 某个元素
     * @return true存在,false不存在
     */
    public static Boolean sismember(String key,String member){
        Jedis jedis = null;
        Boolean isMember = false;
        try {
            jedis = getJedis();
            isMember = jedis.sismember(key, member);
        }finally {
            if (jedis != null){
                jedis.close();
            }
        }
        return isMember;
    }
 
    /**
     * 返回set集合的长度
     * @param key key
     * @return
     */
    public static Long scard(String key){
        Jedis jedis = null;
        Long len = 0L;
        try {
            jedis = getJedis();
            len = jedis.scard(key);
        }finally {
            if (jedis != null){
                jedis.close();
            }
        }
        return len;
    }
 
    /**
     * 删除set集合中指定的一个或多个元素
     * @param key
     * @param members 要删除的元素
     * @return 删除成功的元素个数
     */
    public static Long srem(String key,String... members){
        Jedis jedis = null;
        Long num = 0L;
        try {
            jedis = getJedis();
            num = jedis.srem(key,members);
        }finally {
            if (jedis != null){
                jedis.close();
            }
        }
        return num;
    }
 
    /**
     * 将key1中的元素key1Member移动到key2中
     * @param key1 来源集合key
     * @param key2 目的地集合key
     * @param key1Member key1中的元素
     * @return 1成功,0失败
     */
    public static Long smove(String key1,String key2,String key1Member){
        Jedis jedis = null;
        Long num = 0L;
        try {
            jedis = getJedis();
            num = jedis.smove(key1,key2,key1Member);
        }finally {
            if (jedis != null){
                jedis.close();
            }
        }
        return num;
    }
 
    /**
     * 随机查询返回集合中的指定个数的元素(若count为负数,返回的元素可能会重复)
     * @param key key
     * @param count 要查询返回的元素个数
     * @return 元素list集合
     */
    public static List<String> srandmember(String key,int count){
        Jedis jedis = null;
        List<String> members = null;
        try {
            jedis = getJedis();
            members = jedis.srandmember(key,count);
        }finally {
            if (jedis != null){
                jedis.close();
            }
        }
        return members;
    }
 
    /**
     * 从set集合中随机弹出指定个数个元素
     * @param key key
     * @param count 要弹出的个数
     * @return 随机弹出的元素
     */
    public static Set<String> spop(String key,int count){
        Jedis jedis = null;
        Set<String> members = null;
        try {
            jedis = getJedis();
            members = jedis.spop(key,count);
        }finally {
            if (jedis != null){
                jedis.close();
            }
        }
        return members;
    }
 
    /**
     * 求交集,返回多个set集合相交的部分
     * @param setKeys 多个set集合的key
     * @return 相交的元素集合
     */
    public static Set<String> sinter(String... setKeys){
        Jedis jedis = null;
        Set<String> members = null;
        try {
            jedis = getJedis();
            members = jedis.sinter(setKeys);
        }finally {
            if (jedis != null){
                jedis.close();
            }
        }
        return members;
    }
 
    /**
     * 求并集,求几个set集合的并集(因为set中不会有重复的元素,合并后的集合也不会有重复的元素)
     * @param setKeys 多个set的key
     * @return 合并后的集合
     */
    public static Set<String> sunion(String... setKeys){
        Jedis jedis = null;
        Set<String> members = null;
        try {
            jedis = getJedis();
            members = jedis.sunion(setKeys);
        }finally {
            if (jedis != null){
                jedis.close();
            }
        }
        return members;
    }
 
    /**
     * 求差集,求几个集合之间的差集
     * @param setKeys 多个set的key
     * @return 差集
     */
    public static Set<String> sdiff(String... setKeys){
        Jedis jedis = null;
        Set<String> members = null;
        try {
            jedis = getJedis();
            members = jedis.sdiff(setKeys);
        }finally {
            if (jedis != null){
                jedis.close();
            }
        }
        return members;
    }
 
 
    /*########################  zset(有序集合)的操作  #######################*/
 
    /**
     * 添加一个元素到zset
     * @param key key
     * @param score 元素的分数
     * @param member 元素
     * @return 成功添加的元素个数
     */
    public static Long zadd(String key,double score, String member){
        Jedis jedis = null;
        Long num = null;
        try {
            jedis = getJedis();
            num = jedis.zadd(key,score,member);
        }finally {
            if (jedis != null){
                jedis.close();
            }
        }
        return num;
    }
}

 

 

 

 

 

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐