天天看點

Java 使用Jedis和RedisTemplate操作Redis緩存(SpringBoot)

package com.example.redis.controller;
 
import com.example.redis.entity.User;
import com.example.redis.util.JedisUtil;
import com.example.redis.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.json.JSONObject;
import org.json.JSONException;
 
import java.util.HashMap;
import java.util.Map;
 
@Controller
@RequestMapping(value = "/redis")
public class RedisController {
    @Autowired
    private RedisTemplate redisTemplate = null;
 
    @Autowired
    private StringRedisTemplate stringRedisTemplate = null;
 
    @Autowired
    private RedisUtil redisUtil = null;
 
    @Autowired
    private JedisUtil jedisUtil = null;
 
    @RequestMapping(value = "/test")
    @ResponseBody
    public Map<String, Object> test() throws JSONException {
        //System.out.printf("ip: %s port: %s password: %s ", redisHost, redisPort, redisPassword);
 
        //jedis操作
        //jedisUtil.set("lisi", "李四");
        //redis template操作redis
        //redisUtil.set("zhangsan", "張三");
 
        /**
         * Jedis是Redis官方推薦的面向Java的操作Redis的用戶端,
         *
         * RedisTemplate是SpringDataRedis中對JedisApi的高度封裝。
         * SpringDataRedis相對于Jedis來說可以友善地更換Redis的Java用戶端,比Jedis多了自動管理連接配接池的特性,
         * 友善與其他Spring架構進行搭配使用如:SpringCache支援 jedis和lettuce
         **/
 
 
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            Object zhangsan = redisUtil.get("zhangsan");
            //System.out.println("zhangsan" + zhangsan);
 
            /* 使用雙重驗證鎖解決高并發環境下的緩存穿透問題 */
            if (StringUtils.isEmpty(zhangsan)) { // 第一重驗證
                synchronized (this) {
                    zhangsan = redisUtil.get("zhangsan");
                    if (StringUtils.isEmpty(zhangsan)) { // 第二重驗證
                        System.out.println("查詢資料庫............");
                        // 緩存為空,則查詢資料庫将相關資料存儲到redis中
                        redisUtil.set("zhangsan", "張三",10); //10秒後過期
                    } else {
                        System.out.println("2 查詢緩存............");
                    }
                }
            } else {
                System.out.println("1 查詢緩存............");
            }
 
            map.put("success", true);
 
            entity實體類
            //User user = new User();
            //user.setUserId(1000);
            //user.setUserName("張三");
            //user.setAddress("深圳市南山區");
            //user.setMobile("13988886666");
            //redisUtil.set("userInfo", user.toString(), 10);  //10秒後過期自動删除
            擷取顯示
            //String str = String.valueOf(redisUtil.get("userInfo"));
            //JSONObject jsonObj = new JSONObject(str);
            //map.put("userInfo", jsonObj.get("userId"));
        } catch (Exception e) {
            map.put("success", false);
            e.printStackTrace();
        } finally {
        }
        return map;
    }
 
    /**
     * 操作redis字元串和hash散列
     *
     * @return
     * @Date 2018年11月1日 下午1:56:30
     * @Author lay
     */
    @RequestMapping(value = "/stringAndHash")
    @ResponseBody
    public Map<String, Object> testStringAndHash() {
        //set字元串
        redisTemplate.opsForValue().set("key1", "value1");
        System.out.println("-------------set字元串-------------------: " + redisTemplate.opsForValue().get("key1"));
 
        //定義一個hashmap散列
        Map<String, String> hash = new HashMap<String, String>();
        hash.put("field1", "value1");
        hash.put("field2", "value2");
        //存入一個散列資料類型
        stringRedisTemplate.opsForHash().putAll("hash", hash);
        System.out.println("-------------存入一個散列資料類型-------------------: ");
 
 
        System.out.println("-------------map 周遊-------------------: ");
        redisTemplate.opsForHash().entries("hash").forEach((k, v) -> {
            System.out.println(k + ": " + v);
        });
        System.out.println("-------------map->set 周遊-------------------: ");
        redisTemplate.opsForHash().keys("hash").forEach(key -> {
            System.out.println(key + ": " + redisTemplate.opsForHash().get("hash", key));
        });
 
 
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("success", true);
        return map;
    }
}

package com.example.redis.util;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.BinaryClient;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
 
import java.util.List;
import java.util.Map;
import java.util.Set;
 
/**
 * JedisUtil工具類
 */
@Component
public class JedisUtil {
    private JedisPool pool = null;
 
    @Autowired
    private PropertiesUtils propertiesUtils = null;
 
    private JedisUtil() {
        System.out.println("JedisUtil.JedisUtil");
 
        if (pool == null) {
            propertiesUtils = new PropertiesUtils();
            String ip = String.valueOf(propertiesUtils.getYml("spring.redis.host"));
            int port = Integer.valueOf(propertiesUtils.getYml("spring.redis.port").toString());
            String password = String.valueOf(propertiesUtils.getYml("spring.redis.password"));
            JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
            System.out.printf("----------------ip: %s port: %s password: %s ----------------", ip, port, password);
            //jedisPoolConfig.setMaxTotal(SysConfigUtil.getSysConfigUtil("redis.properties").getInt("redis.maxTotal"));
            //jedisPoolConfig.setMaxIdle(SysConfigUtil.getSysConfigUtil("redis.properties").getInt("redis.maxIdle"));
            //jedisPoolConfig.setMaxWaitMillis(SysConfigUtil.getSysConfigUtil("redis.properties").getLong("redis.maxWaitMillis"));
            //jedisPoolConfig.setTestOnBorrow(SysConfigUtil.getSysConfigUtil("redis.properties").getBoolean("redis.testOnBorrow"));
            if (password != null && !"".equals(password)) {
                // redis 設定了密碼
                pool = new JedisPool(jedisPoolConfig, ip, port, 10000, password);
            } else {
                // redis 未設定密碼
                pool = new JedisPool(jedisPoolConfig, ip, port, 10000);
            }
        }
    }
 
    /**
     * 擷取指定key的值,如果key不存在傳回null,如果該Key存儲的不是字元串,會抛出一個錯誤
     *
     * @param key
     * @return
     */
    public String get(String key) {
        Jedis jedis = getJedis();
        String value = null;
        value = jedis.get(key);
        return value;
    }
 
    /**
     * 設定key的值為value
     *
     * @param key
     * @param value
     * @return
     */
    public String set(String key, String value) {
        Jedis jedis = getJedis();
        return jedis.set(key, value);
    }
 
    /**
     * 删除指定的key,也可以傳入一個包含key的數組
     *
     * @param keys
     * @return
     */
    public Long del(String... keys) {
        Jedis jedis = getJedis();
        return jedis.del(keys);
    }
 
    /**
     * 通過key向指定的value值追加值
     *
     * @param key
     * @param str
     * @return
     */
    public Long append(String key, String str) {
        Jedis jedis = getJedis();
        return jedis.append(key, str);
    }
 
    /**
     * 判斷key是否存在
     *
     * @param key
     * @return
     */
    public Boolean exists(String key) {
        Jedis jedis = getJedis();
        return jedis.exists(key);
    }
 
    /**
     * 設定key value,如果key已經存在則傳回0
     *
     * @param key
     * @param value
     * @return
     */
    public Long setnx(String key, String value) {
        Jedis jedis = getJedis();
        return jedis.setnx(key, value);
    }
 
    /**
     * 設定key value并指定這個鍵值的有效期
     *
     * @param key
     * @param seconds
     * @param value
     * @return
     */
    public String setex(String key, int seconds, String value) {
        Jedis jedis = getJedis();
        return jedis.setex(key, seconds, value);
    }
 
    /**
     * 通過key 和offset 從指定的位置開始将原先value替換
     *
     * @param key
     * @param offset
     * @param str
     * @return
     */
    public Long setrange(String key, int offset, String str) {
        Jedis jedis = getJedis();
        return jedis.setrange(key, offset, str);
    }
 
    /**
     * 通過批量的key擷取批量的value
     *
     * @param keys
     * @return
     */
    public List<String> mget(String... keys) {
        Jedis jedis = getJedis();
        return jedis.mget(keys);
    }
 
    /**
     * 批量的設定key:value,也可以一個
     *
     * @param keysValues
     * @return
     */
    public String mset(String... keysValues) {
        Jedis jedis = getJedis();
        return jedis.mset(keysValues);
    }
 
    /**
     * 批量的設定key:value,可以一個,如果key已經存在則會失敗,操作會復原
     *
     * @param keysValues
     * @return
     */
    public Long msetnx(String... keysValues) {
        Jedis jedis = getJedis();
        return jedis.msetnx(keysValues);
    }
 
    /**
     * 設定key的值,并傳回一個舊值
     *
     * @param key
     * @param value
     * @return
     */
    public String getSet(String key, String value) {
        Jedis jedis = getJedis();
        return jedis.getSet(key, value);
    }
 
    /**
     * 通過下标 和key 擷取指定下标位置的 value
     *
     * @param key
     * @param startOffset
     * @param endOffset
     * @return
     */
    public String getrange(String key, int startOffset, int endOffset) {
        Jedis jedis = getJedis();
        return jedis.getrange(key, startOffset, endOffset);
    }
 
    /**
     * 通過key 對value進行加值+1操作,當value不是int類型時會傳回錯誤,當key不存在是則value為1
     *
     * @param key
     * @return
     */
    public Long incr(String key) {
        Jedis jedis = getJedis();
        return jedis.incr(key);
    }
 
    /**
     * 通過key給指定的value加值,如果key不存在,則這是value為該值
     *
     * @param key
     * @param integer
     * @return
     */
    public Long incrBy(String key, long integer) {
        Jedis jedis = getJedis();
        return jedis.incrBy(key, integer);
    }
 
    /**
     * 對key的值做減減操作,如果key不存在,則設定key為-1
     *
     * @param key
     * @return
     */
    public Long decr(String key) {
        Jedis jedis = getJedis();
        return jedis.decr(key);
    }
 
    /**
     * 減去指定的值
     *
     * @param key
     * @param integer
     * @return
     */
    public Long decrBy(String key, long integer) {
        Jedis jedis = getJedis();
        return jedis.decrBy(key, integer);
    }
 
    /**
     * 通過key擷取value值的長度
     *
     * @param key
     * @return
     */
    public Long strLen(String key) {
        Jedis jedis = getJedis();
        return jedis.strlen(key);
    }
 
    /**
     * 通過key給field設定指定的值,如果key不存在則先建立,如果field已經存在,傳回0
     *
     * @param key
     * @param field
     * @param value
     * @return
     */
    public Long hsetnx(String key, String field, String value) {
        Jedis jedis = getJedis();
        return jedis.hsetnx(key, field, value);
    }
 
    /**
     * 通過key給field設定指定的值,如果key不存在,則先建立
     *
     * @param key
     * @param field
     * @param value
     * @return
     */
    public Long hset(String key, String field, String value) {
        Jedis jedis = getJedis();
        return jedis.hset(key, field, value);
    }
 
    /**
     * 通過key同時設定 hash的多個field
     *
     * @param key
     * @param hash
     * @return
     */
    public String hmset(String key, Map<String, String> hash) {
        Jedis jedis = getJedis();
        return jedis.hmset(key, hash);
    }
 
    /**
     * 通過key 和 field 擷取指定的 value
     *
     * @param key
     * @param failed
     * @return
     */
    public String hget(String key, String failed) {
        Jedis jedis = getJedis();
        return jedis.hget(key, failed);
    }
 
    /**
     * 設定key的逾時時間為seconds
     *
     * @param key
     * @param seconds
     * @return
     */
    public Long expire(String key, int seconds) {
        Jedis jedis = getJedis();
        return jedis.expire(key, seconds);
    }
 
    /**
     * 通過key 和 fields 擷取指定的value 如果沒有對應的value則傳回null
     *
     * @param key
     * @param fields 可以是 一個String 也可以是 String數組
     * @return
     */
    public List<String> hmget(String key, String... fields) {
        Jedis jedis = getJedis();
        return jedis.hmget(key, fields);
    }
 
    /**
     * 通過key給指定的field的value加上給定的值
     *
     * @param key
     * @param field
     * @param value
     * @return
     */
    public Long hincrby(String key, String field, Long value) {
        Jedis jedis = getJedis();
        return jedis.hincrBy(key, field, value);
    }
 
    /**
     * 通過key和field判斷是否有指定的value存在
     *
     * @param key
     * @param field
     * @return
     */
    public Boolean hexists(String key, String field) {
        Jedis jedis = getJedis();
        return jedis.hexists(key, field);
    }
 
    /**
     * 通過key傳回field的數量
     *
     * @param key
     * @return
     */
    public Long hlen(String key) {
        Jedis jedis = getJedis();
        return jedis.hlen(key);
    }
 
    /**
     * 通過key 删除指定的 field
     *
     * @param key
     * @param fields 可以是 一個 field 也可以是 一個數組
     * @return
     */
    public Long hdel(String key, String... fields) {
        Jedis jedis = getJedis();
        return jedis.hdel(key, fields);
    }
 
    /**
     * 通過key傳回所有的field
     *
     * @param key
     * @return
     */
    public Set<String> hkeys(String key) {
        Jedis jedis = getJedis();
        return jedis.hkeys(key);
    }
 
    /**
     * 通過key傳回所有和key有關的value
     *
     * @param key
     * @return
     */
    public List<String> hvals(String key) {
        Jedis jedis = getJedis();
        return jedis.hvals(key);
    }
 
    /**
     * 通過key擷取所有的field和value
     *
     * @param key
     * @return
     */
    public Map<String, String> hgetall(String key) {
        Jedis jedis = getJedis();
        return jedis.hgetAll(key);
    }
 
    /**
     * 通過key向list頭部添加字元串
     *
     * @param key
     * @param strs 可以是一個string 也可以是string數組
     * @return 傳回list的value個數
     */
    public Long lpush(String key, String... strs) {
        Jedis jedis = getJedis();
        return jedis.lpush(key, strs);
    }
 
    /**
     * 通過key向list尾部添加字元串
     *
     * @param key
     * @param strs 可以是一個string 也可以是string數組
     * @return 傳回list的value個數
     */
    public Long rpush(String key, String... strs) {
        Jedis jedis = getJedis();
        return jedis.rpush(key, strs);
    }
 
    /**
     * 通過key在list指定的位置之前或者之後 添加字元串元素
     *
     * @param key
     * @param where LIST_POSITION枚舉類型
     * @param pivot list裡面的value
     * @param value 添加的value
     * @return
     */
    public Long linsert(String key, BinaryClient.LIST_POSITION where,
                        String pivot, String value) {
        Jedis jedis = getJedis();
        return jedis.linsert(key, where, pivot, value);
    }
 
    /**
     * 通過key設定list指定下标位置的value
     * 如果下标超過list裡面value的個數則報錯
     *
     * @param key
     * @param index 從0開始
     * @param value
     * @return 成功傳回OK
     */
    public String lset(String key, Long index, String value) {
        Jedis jedis = getJedis();
        return jedis.lset(key, index, value);
    }
 
    /**
     * 通過key從對應的list中删除指定的count個 和 value相同的元素
     *
     * @param key
     * @param count 當count為0時删除全部
     * @param value
     * @return 傳回被删除的個數
     */
    public Long lrem(String key, long count, String value) {
        Jedis jedis = getJedis();
        return jedis.lrem(key, count, value);
    }
 
    /**
     * 通過key保留list中從strat下标開始到end下标結束的value值
     *
     * @param key
     * @param start
     * @param end
     * @return 成功傳回OK
     */
    public String ltrim(String key, long start, long end) {
        Jedis jedis = getJedis();
        return jedis.ltrim(key, start, end);
    }
 
    /**
     * 通過key從list的頭部删除一個value,并傳回該value
     *
     * @param key
     * @return
     */
    public synchronized String lpop(String key) {
 
        Jedis jedis = getJedis();
        return jedis.lpop(key);
    }
 
    /**
     * 通過key從list尾部删除一個value,并傳回該元素
     *
     * @param key
     * @return
     */
    synchronized public String rpop(String key) {
        Jedis jedis = getJedis();
        return jedis.rpop(key);
    }
 
    /**
     * 通過key從一個list的尾部删除一個value并添加到另一個list的頭部,并傳回該value
     * 如果第一個list為空或者不存在則傳回null
     *
     * @param srckey
     * @param dstkey
     * @return
     */
    public String rpoplpush(String srckey, String dstkey) {
        Jedis jedis = getJedis();
        return jedis.rpoplpush(srckey, dstkey);
    }
 
    /**
     * 通過key擷取list中指定下标位置的value
     *
     * @param key
     * @param index
     * @return 如果沒有傳回null
     */
    public String lindex(String key, long index) {
        Jedis jedis = getJedis();
        return jedis.lindex(key, index);
    }
 
    /**
     * 通過key傳回list的長度
     *
     * @param key
     * @return
     */
    public Long llen(String key) {
        Jedis jedis = getJedis();
        return jedis.llen(key);
    }
 
    /**
     * 通過key擷取list指定下标位置的value
     * 如果start 為 0 end 為 -1 則傳回全部的list中的value
     *
     * @param key
     * @param start
     * @param end
     * @return
     */
    public List<String> lrange(String key, long start, long end) {
        Jedis jedis = getJedis();
        return jedis.lrange(key, start, end);
    }
 
    /**
     * 通過key向指定的set中添加value
     *
     * @param key
     * @param members 可以是一個String 也可以是一個String數組
     * @return 添加成功的個數
     */
    public Long sadd(String key, String... members) {
        Jedis jedis = getJedis();
        return jedis.sadd(key, members);
    }
 
    /**
     * 通過key删除set中對應的value值
     *
     * @param key
     * @param members 可以是一個String 也可以是一個String數組
     * @return 删除的個數
     */
    public Long srem(String key, String... members) {
        Jedis jedis = getJedis();
        return jedis.srem(key, members);
    }
 
    /**
     * 通過key随機删除一個set中的value并傳回該值
     *
     * @param key
     * @return
     */
    public String spop(String key) {
        Jedis jedis = getJedis();
        return jedis.spop(key);
    }
 
    /**
     * 通過key擷取set中的差集
     * 以第一個set為标準
     *
     * @param keys 可以 是一個string 則傳回set中所有的value 也可以是string數組
     * @return
     */
    public Set<String> sdiff(String... keys) {
        Jedis jedis = getJedis();
        return jedis.sdiff(keys);
    }
 
    /**
     * 通過key擷取set中的差集并存入到另一個key中
     * 以第一個set為标準
     *
     * @param dstkey 差集存入的key
     * @param keys   可以 是一個string 則傳回set中所有的value 也可以是string數組
     * @return
     */
    public Long sdiffstore(String dstkey, String... keys) {
        Jedis jedis = getJedis();
        return jedis.sdiffstore(dstkey, keys);
    }
 
    /**
     * 通過key擷取指定set中的交集
     *
     * @param keys 可以 是一個string 也可以是一個string數組
     * @return
     */
    public Set<String> sinter(String... keys) {
        Jedis jedis = getJedis();
        return jedis.sinter(keys);
    }
 
    /**
     * 通過key擷取指定set中的交集 并将結果存入新的set中
     *
     * @param dstkey
     * @param keys   可以 是一個string 也可以是一個string數組
     * @return
     */
    public Long sinterstore(String dstkey, String... keys) {
        Jedis jedis = getJedis();
        return jedis.sinterstore(dstkey, keys);
    }
 
    /**
     * 通過key傳回所有set的并集
     *
     * @param keys 可以 是一個string 也可以是一個string數組
     * @return
     */
    public Set<String> sunion(String... keys) {
        Jedis jedis = getJedis();
        return jedis.sunion(keys);
    }
 
    /**
     * 通過key傳回所有set的并集,并存入到新的set中
     *
     * @param dstkey
     * @param keys   可以 是一個string 也可以是一個string數組
     * @return
     */
    public Long sunionstore(String dstkey, String... keys) {
        Jedis jedis = getJedis();
        return jedis.sunionstore(dstkey, keys);
    }
 
    /**
     * 通過key将set中的value移除并添加到第二個set中
     *
     * @param srckey 需要移除的
     * @param dstkey 添加的
     * @param member set中的value
     * @return
     */
    public Long smove(String srckey, String dstkey, String member) {
        Jedis jedis = getJedis();
        return jedis.smove(srckey, dstkey, member);
    }
 
    /**
     * 通過key擷取set中value的個數
     *
     * @param key
     * @return
     */
    public Long scard(String key) {
        Jedis jedis = getJedis();
        return jedis.scard(key);
    }
 
    /**
     * 通過key判斷value是否是set中的元素
     *
     * @param key
     * @param member
     * @return
     */
    public Boolean sismember(String key, String member) {
        Jedis jedis = getJedis();
        return jedis.sismember(key, member);
    }
 
    /**
     * 通過key擷取set中随機的value,不删除元素
     *
     * @param key
     * @return
     */
    public String srandmember(String key) {
        Jedis jedis = getJedis();
        return jedis.srandmember(key);
    }
 
    /**
     * 通過key擷取set中所有的value
     *
     * @param key
     * @return
     */
    public Set<String> smembers(String key) {
        Jedis jedis = getJedis();
        return jedis.smembers(key);
    }
 
 
    /**
     * 通過key向zset中添加value,score,其中score就是用來排序的
     * 如果該value已經存在則根據score更新元素
     *
     * @param key
     * @param score
     * @param member
     * @return
     */
    public Long zadd(String key, double score, String member) {
        Jedis jedis = getJedis();
        return jedis.zadd(key, score, member);
    }
 
    /**
     * 通過key删除在zset中指定的value
     *
     * @param key
     * @param members 可以 是一個string 也可以是一個string數組
     * @return
     */
    public Long zrem(String key, String... members) {
        Jedis jedis = getJedis();
        return jedis.zrem(key, members);
    }
 
    /**
     * 通過key增加該zset中value的score的值
     *
     * @param key
     * @param score
     * @param member
     * @return
     */
    public Double zincrby(String key, double score, String member) {
        Jedis jedis = getJedis();
        return jedis.zincrby(key, score, member);
    }
 
    /**
     * 通過key傳回zset中value的排名
     * 下标從小到大排序
     *
     * @param key
     * @param member
     * @return
     */
    public Long zrank(String key, String member) {
        Jedis jedis = getJedis();
        return jedis.zrank(key, member);
    }
 
    /**
     * 通過key傳回zset中value的排名
     * 下标從大到小排序
     *
     * @param key
     * @param member
     * @return
     */
    public Long zrevrank(String key, String member) {
        Jedis jedis = getJedis();
        return jedis.zrevrank(key, member);
    }
 
    /**
     * 通過key将擷取score從start到end中zset的value
     * socre從大到小排序
     * 當start為0 end為-1時傳回全部
     *
     * @param key
     * @param start
     * @param end
     * @return
     */
    public Set<String> zrevrange(String key, long start, long end) {
        Jedis jedis = getJedis();
        return jedis.zrevrange(key, start, end);
    }
 
    /**
     * 通過key傳回指定score内zset中的value
     *
     * @param key
     * @param max
     * @param min
     * @return
     */
    public Set<String> zrangebyscore(String key, String max, String min) {
        Jedis jedis = getJedis();
        return jedis.zrevrangeByScore(key, max, min);
    }
 
    /**
     * 通過key傳回指定score内zset中的value
     *
     * @param key
     * @param max
     * @param min
     * @return
     */
    public Set<String> zrangeByScore(String key, double max, double min) {
        Jedis jedis = getJedis();
        return jedis.zrevrangeByScore(key, max, min);
    }
 
    /**
     * 傳回指定區間内zset中value的數量
     *
     * @param key
     * @param min
     * @param max
     * @return
     */
    public Long zcount(String key, String min, String max) {
        Jedis jedis = getJedis();
        return jedis.zcount(key, min, max);
    }
 
    /**
     * 通過key傳回zset中的value個數
     *
     * @param key
     * @return
     */
    public Long zcard(String key) {
        Jedis jedis = getJedis();
        return jedis.zcard(key);
    }
 
    /**
     * 通過key擷取zset中value的score值
     *
     * @param key
     * @param member
     * @return
     */
    public Double zscore(String key, String member) {
        Jedis jedis = getJedis();
        return jedis.zscore(key, member);
    }
 
    /**
     * 通過key删除給定區間内的元素
     *
     * @param key
     * @param start
     * @param end
     * @return
     */
    public Long zremrangeByRank(String key, long start, long end) {
        Jedis jedis = getJedis();
        return jedis.zremrangeByRank(key, start, end);
    }
 
    /**
     * 通過key删除指定score内的元素
     *
     * @param key
     * @param start
     * @param end
     * @return
     */
    public Long zremrangeByScore(String key, double start, double end) {
        Jedis jedis = getJedis();
        return jedis.zremrangeByScore(key, start, end);
    }
 
    /**
     * 傳回滿足pattern表達式的所有key
     * keys(*)
     * 傳回所有的key
     *
     * @param pattern
     * @return
     */
    public Set<String> keys(String pattern) {
        Jedis jedis = getJedis();
        return jedis.keys(pattern);
    }
 
    /**
     * 通過key判斷值得類型
     *
     * @param key
     * @return
     */
    public String type(String key) {
        Jedis jedis = getJedis();
        return jedis.type(key);
    }
 
 
    private void close(Jedis jedis) {
        if (jedis != null) {
            jedis.close();
        }
    }
 
    private Jedis getJedis() {
        return pool.getResource();
    }
 
    public static RedisUtil getRedisUtil() {
        return new RedisUtil();
    }
 
}

package com.example.redis.util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
 
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
 
/**
 * RedisTemplate 工具類
 */
@Component
public class RedisUtil {
    @Autowired
    private RedisTemplate redisTemplate;
 
 
    //- - - - - - - - - - - - - - - - - - - - -  公共方法 - - - - - - - - - - - - - - - - - - - -
 
    /**
     * 給一個指定的 key 值附加過期時間
     *
     * @param key
     * @param time
     * @return
     */
    public boolean expire(String key, long time) {
        return redisTemplate.expire(key, time, TimeUnit.SECONDS);
    }
 
    /**
     * 根據key 擷取過期時間
     *
     * @param key
     * @return
     */
    public long getTime(String key) {
        return redisTemplate.getExpire(key, TimeUnit.SECONDS);
    }
 
    /**
     * 根據key 擷取過期時間
     *
     * @param key
     * @return
     */
    public boolean hasKey(String key) {
        return redisTemplate.hasKey(key);
    }
 
    /**
     * 移除指定key 的過期時間
     *
     * @param key
     * @return
     */
    public boolean persist(String key) {
        return redisTemplate.boundValueOps(key).persist();
    }
 
    //- - - - - - - - - - - - - - - - - - - - -  String類型 - - - - - - - - - - - - - - - - - - - -
 
    /**
     * 根據key擷取值
     *
     * @param key 鍵
     * @return 值
     */
    public Object get(String key) {
        return key == null ? null : redisTemplate.opsForValue().get(key);
    }
 
    /**
     * 将值放入緩存
     *
     * @param key   鍵
     * @param value 值
     * @return true成功 false 失敗
     */
    public void set(String key, String value) {
        redisTemplate.opsForValue().set(key, value);
    }
 
    /**
     * 将值放入緩存并設定時間
     *
     * @param key   鍵
     * @param value 值
     * @param time  時間(秒) -1為無期限
     * @return true成功 false 失敗
     */
    public void set(String key, String value, long time) {
        if (time > 0) {
            redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
        } else {
            redisTemplate.opsForValue().set(key, value);
        }
    }
 
    /**
     * 批量添加 key (重複的鍵會覆寫)
     *
     * @param keyAndValue
     */
    public void batchSet(Map<String, String> keyAndValue) {
        redisTemplate.opsForValue().multiSet(keyAndValue);
    }
 
    /**
     * 批量添加 key-value 隻有在鍵不存在時,才添加
     * map 中隻要有一個key存在,則全部不添加
     *
     * @param keyAndValue
     */
    public void batchSetIfAbsent(Map<String, String> keyAndValue) {
        redisTemplate.opsForValue().multiSetIfAbsent(keyAndValue);
    }
 
    /**
     * 對一個 key-value 的值進行加減操作,
     * 如果該 key 不存在 将建立一個key 并指派該 number
     * 如果 key 存在,但 value 不是長整型 ,将報錯
     *
     * @param key
     * @param number
     */
    public Long increment(String key, long number) {
        return redisTemplate.opsForValue().increment(key, number);
    }
 
    /**
     * 對一個 key-value 的值進行加減操作,
     * 如果該 key 不存在 将建立一個key 并指派該 number
     * 如果 key 存在,但 value 不是 純數字 ,将報錯
     *
     * @param key
     * @param number
     */
    public Double increment(String key, double number) {
        return redisTemplate.opsForValue().increment(key, number);
    }
 
    //- - - - - - - - - - - - - - - - - - - - -  set類型 - - - - - - - - - - - - - - - - - - - -
 
    /**
     * 将資料放入set緩存
     *
     * @param key 鍵
     * @return
     */
    public void sSet(String key, String value) {
        redisTemplate.opsForSet().add(key, value);
    }
 
    /**
     * 擷取變量中的值
     *
     * @param key 鍵
     * @return
     */
    public Set<Object> members(String key) {
        return redisTemplate.opsForSet().members(key);
    }
 
    /**
     * 随機擷取變量中指定個數的元素
     *
     * @param key   鍵
     * @param count 值
     * @return
     */
    public void randomMembers(String key, long count) {
        redisTemplate.opsForSet().randomMembers(key, count);
    }
 
    /**
     * 随機擷取變量中的元素
     *
     * @param key 鍵
     * @return
     */
    public Object randomMember(String key) {
        return redisTemplate.opsForSet().randomMember(key);
    }
 
    /**
     * 彈出變量中的元素
     *
     * @param key 鍵
     * @return
     */
    public Object pop(String key) {
        return redisTemplate.opsForSet().pop("setValue");
    }
 
    /**
     * 擷取變量中值的長度
     *
     * @param key 鍵
     * @return
     */
    public long size(String key) {
        return redisTemplate.opsForSet().size(key);
    }
 
    /**
     * 根據value從一個set中查詢,是否存在
     *
     * @param key   鍵
     * @param value 值
     * @return true 存在 false不存在
     */
    public boolean sHasKey(String key, Object value) {
        return redisTemplate.opsForSet().isMember(key, value);
    }
 
    /**
     * 檢查給定的元素是否在變量中。
     *
     * @param key 鍵
     * @param obj 元素對象
     * @return
     */
    public boolean isMember(String key, Object obj) {
        return redisTemplate.opsForSet().isMember(key, obj);
    }
 
    /**
     * 轉移變量的元素值到目的變量。
     *
     * @param key     鍵
     * @param value   元素對象
     * @param destKey 元素對象
     * @return
     */
    public boolean move(String key, String value, String destKey) {
        return redisTemplate.opsForSet().move(key, value, destKey);
    }
 
    /**
     * 批量移除set緩存中元素
     *
     * @param key    鍵
     * @param values 值
     * @return
     */
    public void remove(String key, Object... values) {
        redisTemplate.opsForSet().remove(key, values);
    }
 
    /**
     * 通過給定的key求2個set變量的內插補點
     *
     * @param key     鍵
     * @param destKey 鍵
     * @return
     */
    public Set<Set> difference(String key, String destKey) {
        return redisTemplate.opsForSet().difference(key, destKey);
    }
 
 
    //- - - - - - - - - - - - - - - - - - - - -  hash類型 - - - - - - - - - - - - - - - - - - - -
 
    /**
     * 加入緩存
     *
     * @param key 鍵
     * @param map 鍵
     * @return
     */
    public void add(String key, Map<String, String> map) {
        redisTemplate.opsForHash().putAll(key, map);
    }
 
    /**
     * 擷取 key 下的 所有  hashkey 和 value
     *
     * @param key 鍵
     * @return
     */
    public Map<Object, Object> getHashEntries(String key) {
        return redisTemplate.opsForHash().entries(key);
    }
 
    /**
     * 驗證指定 key 下 有沒有指定的 hashkey
     *
     * @param key
     * @param hashKey
     * @return
     */
    public boolean hashKey(String key, String hashKey) {
        return redisTemplate.opsForHash().hasKey(key, hashKey);
    }
 
    /**
     * 擷取指定key的值string
     *
     * @param key  鍵
     * @param key2 鍵
     * @return
     */
    public String getMapString(String key, String key2) {
        return redisTemplate.opsForHash().get("map1", "key1").toString();
    }
 
    /**
     * 擷取指定的值Int
     *
     * @param key  鍵
     * @param key2 鍵
     * @return
     */
    public Integer getMapInt(String key, String key2) {
        return (Integer) redisTemplate.opsForHash().get("map1", "key1");
    }
 
    /**
     * 彈出元素并删除
     *
     * @param key 鍵
     * @return
     */
    public String popValue(String key) {
        return redisTemplate.opsForSet().pop(key).toString();
    }
 
    /**
     * 删除指定 hash 的 HashKey
     *
     * @param key
     * @param hashKeys
     * @return 删除成功的 數量
     */
    public Long delete(String key, String... hashKeys) {
        return redisTemplate.opsForHash().delete(key, hashKeys);
    }
 
    /**
     * 給指定 hash 的 hashkey 做增減操作
     *
     * @param key
     * @param hashKey
     * @param number
     * @return
     */
    public Long increment(String key, String hashKey, long number) {
        return redisTemplate.opsForHash().increment(key, hashKey, number);
    }
 
    /**
     * 給指定 hash 的 hashkey 做增減操作
     *
     * @param key
     * @param hashKey
     * @param number
     * @return
     */
    public Double increment(String key, String hashKey, Double number) {
        return redisTemplate.opsForHash().increment(key, hashKey, number);
    }
 
    /**
     * 擷取 key 下的 所有 hashkey 字段
     *
     * @param key
     * @return
     */
    public Set<Object> hashKeys(String key) {
        return redisTemplate.opsForHash().keys(key);
    }
 
    /**
     * 擷取指定 hash 下面的 鍵值對 數量
     *
     * @param key
     * @return
     */
    public Long hashSize(String key) {
        return redisTemplate.opsForHash().size(key);
    }
 
    //- - - - - - - - - - - - - - - - - - - - -  list類型 - - - - - - - - - - - - - - - - - - - -
 
    /**
     * 在變量左邊添加元素值
     *
     * @param key
     * @param value
     * @return
     */
    public void leftPush(String key, Object value) {
        redisTemplate.opsForList().leftPush(key, value);
    }
 
    /**
     * 擷取集合指定位置的值。
     *
     * @param key
     * @param index
     * @return
     */
    public Object index(String key, long index) {
        return redisTemplate.opsForList().index("list", 1);
    }
 
    /**
     * 擷取指定區間的值。
     *
     * @param key
     * @param start
     * @param end
     * @return
     */
    public List<Object> range(String key, long start, long end) {
        return redisTemplate.opsForList().range(key, start, end);
    }
 
    /**
     * 把最後一個參數值放到指定集合的第一個出現中間參數的前面,
     * 如果中間參數值存在的話。
     *
     * @param key
     * @param pivot
     * @param value
     * @return
     */
    public void leftPush(String key, String pivot, String value) {
        redisTemplate.opsForList().leftPush(key, pivot, value);
    }
 
    /**
     * 向左邊批量添加參數元素。
     *
     * @param key
     * @param values
     * @return
     */
    public void leftPushAll(String key, String... values) {
//        redisTemplate.opsForList().leftPushAll(key,"w","x","y");
        redisTemplate.opsForList().leftPushAll(key, values);
    }
 
    /**
     * 向集合最右邊添加元素。
     *
     * @param key
     * @param value
     * @return
     */
    public void leftPushAll(String key, String value) {
        redisTemplate.opsForList().rightPush(key, value);
    }
 
    /**
     * 向左邊批量添加參數元素。
     *
     * @param key
     * @param values
     * @return
     */
    public void rightPushAll(String key, String... values) {
      //redisTemplate.opsForList().leftPushAll(key,"w","x","y");
        redisTemplate.opsForList().rightPushAll(key, values);
    }
 
    /**
     * 向已存在的集合中添加元素。
     *
     * @param key
     * @param value
     * @return
     */
    public void rightPushIfPresent(String key, Object value) {
        redisTemplate.opsForList().rightPushIfPresent(key, value);
    }
 
    /**
     * 向已存在的集合中添加元素。
     *
     * @param key
     * @return
     */
    public long listLength(String key) {
        return redisTemplate.opsForList().size(key);
    }
 
    /**
     * 移除集合中的左邊第一個元素。
     *
     * @param key
     * @return
     */
    public void leftPop(String key) {
        redisTemplate.opsForList().leftPop(key);
    }
 
    /**
     * 移除集合中左邊的元素在等待的時間裡,如果超過等待的時間仍沒有元素則退出。
     *
     * @param key
     * @return
     */
    public void leftPop(String key, long timeout, TimeUnit unit) {
        redisTemplate.opsForList().leftPop(key, timeout, unit);
    }
 
    /**
     * 移除集合中右邊的元素。
     *
     * @param key
     * @return
     */
    public void rightPop(String key) {
        redisTemplate.opsForList().rightPop(key);
    }
 
    /**
     * 移除集合中右邊的元素在等待的時間裡,如果超過等待的時間仍沒有元素則退出。
     *
     * @param key
     * @return
     */
    public void rightPop(String key, long timeout, TimeUnit unit) {
        redisTemplate.opsForList().rightPop(key, timeout, unit);
    }
}