Spring-Boot 使用 Jedis 操做 Redis

背景:java

  1.Redis 以前學了個皮毛 還忘的差很少了,感受公司項目中的Redis用的真的牛逼,so 須要深造。web

  2.有個同事在搞Jedis,勾起了我對知識的嚮往,不會用,可是很渴望。redis

過程:spring

  1.改造原有項目集成Jedis,引入jar包緩存

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

  2.yml中配置Redis 大部分使用的是默認配置網絡

  redis:
    database: 0
    host: localhost
    port: 6379
    password:
    pool:
      max-active: 8
      max-wait: -1
      max-idle: 8
      min-idle: 0
    timeout: 0
  session:
    store-type: none

  3.編寫Jedis配置類 JedisConfigsession

package com.zyt.creenshot.configs;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * @ClassName JedisConfig
 * @Description Jedis配置工具類 夢想家
 * @Author Zhai XiaoTao https://www.cnblogs.com/zhaiyt
 * @Date 2019/1/14 14:45
 * @Version 1.0
 */
@Configuration
@Slf4j
@Data
public class JedisConfig extends CachingConfigurerSupport {

    @Value("${spring.redis.host}")
    private String host;

    @Value("${spring.redis.port}")
    private int port;

    @Value("${spring.redis.timeout}")
    private int timeout;

    @Value("${spring.redis.pool.max-active}")
    private int maxActive;

    @Value("${spring.redis.pool.max-idle}")
    private int maxIdle;

    @Value("${spring.redis.pool.min-idle}")
    private int minIdle;

    @Value("${spring.redis.pool.max-wait}")
    private long maxWaitMillis;

    @Bean
    public JedisPool redisPoolFactory() {
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxIdle(maxIdle);
        jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
        jedisPoolConfig.setMaxTotal(maxActive);
        jedisPoolConfig.setMinIdle(minIdle);
        JedisPool jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout, null);
        log.info("JedisPool注入成功!");
        log.info("redis地址:" + host + ":" + port);
        return jedisPool;
    }
}

  4.編寫JedisUtil工具類 就前面幾個有點用,後面的暫時還沒找到用的地方app

package com.zyt.creenshot.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import sun.plugin2.message.Serializer;

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

/**
 * @ClassName JedisUtil
 * @Description screenShot 夢想家
 * @Author Zhai XiaoTao https://www.cnblogs.com/zhaiyt
 * @Date 2019/1/14 15:04
 * @Version 1.0
 */
@Component
public class JedisUtil {

    @Autowired
    private JedisPool jedisPool;

    @Autowired(required = false)
    private Serializer serializer;

    /**
     * string類型
     *
     * @param key
     * @param value
     * @return
     */
    public String set(String key, String value) {
        Jedis jedis = jedisPool.getResource();
        String back = jedis.set(key, value);
        jedis.close();
        return back;
    }

    /**
     * @return java.util.Set<java.lang.String>
     * @Description <模糊獲取key>
     * @Author Zhaiyt
     * @Date 20:02 2019/1/14
     * @Param
     **/
    public Set<String> keys(String pattern) {
        Jedis jedis = jedisPool.getResource();
        Set<String> keys = jedis.keys(pattern);
        jedis.close();
        return keys;
    }


    /**
     * 刪除key對應的value
     *
     * @param key
     * @return
     */
    public Long del(String key) {
        Jedis jedis = jedisPool.getResource();
        Long back = jedis.del(key);
        jedis.close();
        return back;
    }

    /**
     * 獲取string類型
     *
     * @param key
     * @return
     */
    public String get(String key) {
        Jedis jedis = jedisPool.getResource();
        String back = jedis.get(key);
        jedis.close();
        return back;
    }

    /**
     * 將值 value 關聯到 key ,並將 key 的生存時間設爲 seconds (以秒爲單位)。
     *
     * @param key
     * @param seconds
     * @param value
     * @return
     */
    public String setex(String key, int seconds, String value) {
        Jedis jedis = jedisPool.getResource();
        String back = jedis.setex(key, seconds, value);
        jedis.close();
        return back;
    }

    /**
     * 返回哈希表 key 中,全部的域和值。
     * 在返回值裏,緊跟每一個域名(field name)以後是域的值(value),因此返回值的長度是哈希表大小的兩倍。
     *
     * @param key
     * @return
     */
    public Map hgetAll(String key) {
        Jedis jedis = jedisPool.getResource();
        Map back = jedis.hgetAll(key);
        jedis.close();
        return back;
    }

    /**
     * 將哈希表 key 中的域 field 的值設爲 value 。
     * 若是 key 不存在,一個新的哈希表被建立並進行 HSET 操做。
     * 若是域 field 已經存在於哈希表中,舊值將被覆蓋。
     *
     * @param key
     * @param field
     * @param value
     * @return
     */
    public Long hset(String key, String field, String value) {
        Jedis jedis = jedisPool.getResource();
        Long back = jedis.hset(key, field, value);
        jedis.close();
        return back;
    }

    /**
     * 返回哈希表 key 中給定域 field 的值。
     *
     * @param key
     * @param field
     * @return
     */
    public String hget(String key, String field) {
        Jedis jedis = jedisPool.getResource();
        String back = jedis.hget(key, field);
        jedis.close();
        return back;
    }

    /**
     * 刪除哈希表 key 中的一個或多個指定域,不存在的域將被忽略。
     *
     * @param key
     * @param field
     * @return
     */
    public long hdel(String key, String field) {
        Jedis jedis = jedisPool.getResource();
        long back = jedis.hdel(key, field);
        jedis.close();
        return back;
    }

    /**
     * 將一個或多個值 value 插入到列表 key 的表頭
     *
     * @param key
     * @param value
     * @return
     */
    public Long lpush(String key, String... value) {
        Jedis jedis = jedisPool.getResource();
        Long back = jedis.lpush(key, value);
        jedis.close();
        return back;
    }

    /**
     * 將一個或多個值 value 插入到列表 key 的表尾
     *
     * @param key
     * @param value
     * @return
     */
    public long rpush(String key, String... value) {
        Jedis jedis = jedisPool.getResource();
        long back = jedis.rpush(key, value);
        jedis.close();
        return back;
    }

    /**
     * 經過下標替換元素的內容
     *
     * @param key
     * @param index
     * @param value
     * @return
     */
    public String lset(String key, long index, String value) {
        Jedis jedis = jedisPool.getResource();
        String back = jedis.lset(key, index, value);
        jedis.close();
        return back;
    }

    /**
     * 移除有序集合lsit中的參數
     * 0全部
     *
     * @param key
     * @param count
     * @param value
     * @return
     */
    public long lrem(String key, long count, String value) {
        Jedis jedis = jedisPool.getResource();
        long back = jedis.lrem(key, count, value);
        jedis.close();
        return back;
    }

    /**
     * 返回列表 key 的長度。
     * 若是 key 不存在,則 key 被解釋爲一個空列表,返回 0 .
     * 若是 key 不是列表類型,返回一個錯誤。
     *
     * @param key
     * @return
     */
    public Long llen(String key) {
        Jedis jedis = jedisPool.getResource();
        Long back = jedis.llen(key);
        jedis.close();
        return back;
    }

    /**
     * 返回列表 key 中指定區間內的元素
     * -1 表示列表的最後一個元素
     *
     * @param key
     * @param start
     * @param end
     * @return
     */
    public List lrange(String key, int start, int end) {
        Jedis jedis = jedisPool.getResource();
        List back = jedis.lrange(key, start, end);
        jedis.close();
        return back;
    }

    /**
     * 將 key 中儲存的數字值增一
     *
     * @param key
     * @return
     */
    public long incr(String key) {
        Jedis jedis = jedisPool.getResource();
        long back = jedis.incr(key);
        jedis.close();
        return back;
    }

    /**
     * 將 key 中儲存的數字值減一。
     *
     * @param key
     * @return
     */
    public long decr(String key) {
        Jedis jedis = jedisPool.getResource();
        long back = jedis.decr(key);
        jedis.close();
        return back;
    }

    /**
     * 爲給定 key 設置生存時間,當 key 過時時(生存時間爲 0 ),它會被自動刪除。
     *
     * @param key
     * @param seconds
     * @return
     */
    public long expire(String key, int seconds) {
        Jedis jedis = jedisPool.getResource();
        long back = jedis.expire(key, seconds);
        jedis.close();
        return back;
    }

    /**
     * 將一個或多個 member 元素加入到集合 key 當中,已經存在於集合的 member 元素將被忽略。
     *
     * @param key
     * @param value
     * @return
     */
    public long sadd(String key, String value) {
        Jedis jedis = jedisPool.getResource();
        long back = jedis.sadd(key, value);
        jedis.close();
        return back;
    }

    /**
     * 檢查給定 key 是否存在。
     *
     * @param key
     * @return
     */
    public boolean exists(String key) {
        Jedis jedis = jedisPool.getResource();
        boolean back = jedis.exists(key);
        jedis.close();
        return back;
    }

    /**
     * 將一個或多個 member 元素及其 score 值加入到有序集 key 當中。
     *
     * @param key
     * @param score
     * @param member
     * @return
     */
    public double zadd(String key, double score, String member) {
        Jedis jedis = jedisPool.getResource();
        double back = jedis.zadd(key, score, member);
        jedis.close();
        return back;
    }

    /**
     * 返回有序集 key 中,全部 score 值介於 min 和 max 之間(包括等於 min 或 max )的成員。有序集成員按 score 值遞增(從小到大)次序排列。
     *
     * @param key
     * @param min
     * @param max
     * @return
     */
    public Set getZrangeByScore(String key, String min, String max) {
        Jedis jedis = jedisPool.getResource();
        Set back = jedis.zrangeByScore(key, min, max);
        jedis.close();
        return back;
    }

    /**
     * 移除有序系列中的指定範圍
     *
     * @param key
     * @param start
     * @param end
     * @return
     */
    public long delZremrangeByScore(String key, String start, String end) {
        Jedis jedis = jedisPool.getResource();
        long back = jedis.zremrangeByScore(key, start, end);
        jedis.close();
        return back;
    }

    /**
     * 有序集合
     * 根據分數降序排列
     *
     * @param key
     * @param max
     * @param min
     * @return
     */
    public Set getZrevrangeByScore(String key, String max, String min) {
        Jedis jedis = jedisPool.getResource();
        Set back = jedis.zrevrangeByScore(key, max, min);
        jedis.close();
        return back;
    }

    /**
     * 有序集合
     * score增長或減小值
     *
     * @param key
     * @param score
     * @param member
     * @return
     */
    public Double setZincrby(String key, double score, String member) {
        Jedis jedis = jedisPool.getResource();
        double back = jedis.zincrby(key, score, member);
        jedis.close();
        return back;
    }

    /**
     * 有序集合
     * 降序排列
     *
     * @param key
     * @param start
     * @param end
     * @return
     */
    public Set getZrevrange(String key, long start, long end) {
        Jedis jedis = jedisPool.getResource();
        Set back = jedis.zrevrange(key, start, end);
        jedis.close();
        return back;
    }
}

  5.編寫對象轉字符串 和 字符串轉對象公共方法工具

       /**
         * @Description <對象轉string>
         * @Author Zhaiyt
         * @Date 19:34 2019/1/14
         * @Param
         * @return java.lang.String
         **/
        public static String objectToString(Object obj){
            ObjectMapper objectMapper = new ObjectMapper();
            String resultStr = null;
            try {
                resultStr = objectMapper.writeValueAsString(obj);
            } catch (JsonProcessingException e) {
                log.error("向Redis中寫入數據時失敗");
            }
            return resultStr;
        }

        /**
         * @Description <對象轉string>
         * @Author Zhaiyt
         * @Date 19:34 2019/1/14
         * @Param
         * @return java.lang.String
         **/
        public static Object stringToObj(Class typeClass,Class clazz,String data){
            ObjectMapper objectMapper = new ObjectMapper();
            JavaType javaType = objectMapper.getTypeFactory().constructParametricType(typeClass, clazz);
            Object obj = null;
            try {
                obj = objectMapper.readValue(data, javaType);
            } catch (IOException e) {
                log.error("redis中讀取數據失敗");
            }
            return obj;
        }         

  6.編寫測試方法測試

    /**
     * @Description <Redis test method>
     * @Author Zhaiyt
     * @Date 20:57 2019/1/14
     * @Param
     * @return java.util.List<com.zyt.creenshot.entity.Record>
     **/
    @RequestMapping(value = "/findAll")
    public List<Record> findAll() {
        List<Record> allRecord = null;
        if (jedisUtil.exists("findAll")) {
            return (List<Record>) CommonUtils.stringToObj(List.class, Record.class, jedisUtil.get("findAll"));
        } else {
            allRecord = recordServiceImpl.findAllRecord();
            String str = CommonUtils.objectToString(allRecord);
            jedisUtil.set("findAll", str);
        }
        return allRecord;
    }

  7.編寫清除緩存操做接口類

package com.zyt.creenshot.controller;

import com.zyt.creenshot.util.JedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Set;

/**
 * @ClassName RedisController
 * @Description Redis緩存操做接口 夢想家
 * @Author Zhai XiaoTao https://www.cnblogs.com/zhaiyt
 * @Date 2019/1/14 16:07
 * @Version 1.0
 */
@RestController
@Slf4j
public class RedisController {

    @Autowired
    private JedisUtil jedisUtil;

    /**
     * @return void
     * @Description <清空全部緩存>
     * @Author Zhaiyt
     * @Date 20:19 2019/1/14
     * @Param
     **/
    @RequestMapping(value = "/refrashAllCache")
    public void refrashAllCache() {
        log.info("清空Redis緩存 ... start ... ");
        Set<String> keys = jedisUtil.keys("*");
        for (String key : keys) {
            jedisUtil.del(key);
        }
        log.info("清空Redis緩存 ... end ... ");
    }

    /**
     * @return void
     * @Description <清空制定key緩存>
     * @Author Zhaiyt
     * @Date 20:19 2019/1/14
     * @Param
     **/
    @RequestMapping(value = "/refrashCacheByKey")
    public void refrashCacheByKey(String key) {
        log.info("刪除 key 值爲" + key + "的緩存 ... start ...");
        Set<String> keys = jedisUtil.keys(key);
        jedisUtil.del(key);
        log.info("刪除 key 值爲" + key + "的緩存 ... end ...");
    }

    /**
     * @return void
     * @Description <移除指定類型緩存>
     * @Author Zhaiyt
     * @Date 20:19 2019/1/14
     * @Param
     **/
    @RequestMapping(value = "/refrashCacheByKeyType")
    public void refrashCacheByKeyType(String keyType) {
        log.info("刪除類型爲" + keyType + "的緩存 ... start ...");
        Set<String> keys = jedisUtil.keys(keyType);
        for (String key : keys) {
            jedisUtil.del(key);
        }
        log.info("刪除類型爲" + keyType + "的緩存 ... end ...");
    }
}

  8.啓動Redis忘記了... Redis 安裝參照另外一篇文章或參照 菜鳥網絡的進行安裝啓動,測試 over

相關文章
相關標籤/搜索