zoukankan      html  css  js  c++  java
  • Spring-Boot 使用 Jedis 操作 Redis

    背景:

      1.Redis 之前学了个皮毛 还忘的差不多了,感觉公司项目中的Redis用的真的牛逼,so 需要深造。

      2.有个同事在搞Jedis,勾起了我对知识的向往,不会用,但是很渴望。

    过程:

      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配置类 JedisConfig

    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工具类 就前面几个有点用,后面的暂时还没找到用的地方

    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

      

  • 相关阅读:
    读写分离之Atlas
    数组、集合和可变长参数
    史上最全的maven的pom.xml文件详解
    ArrayList集合与List与数组的区别
    ELK(ElasticSearch, Logstash, Kibana)搭建实时日志分析平台
    Linux下Nagios的安装与配置
    Redis在windows下安装过程
    TortoiseGit-2.0.0.0-64bit问题
    丢用lamp手动安装apache php mysql
    手把手教你小程序对接微信支付
  • 原文地址:https://www.cnblogs.com/zhaiyt/p/10269167.html
Copyright © 2011-2022 走看看