• redis工具类封装


    各位读者,大家好!

        本次给大家带来redis的封装类,可以很优雅的操作redis,本工具结合了springframework中的部分注解和类,适用于spring框架的项目使用。

        首先,创建一个配置类ConstantConfig,可以很方便读取配置文件:

     1 package com.cheng2839.config;
     2 
     3 import lombok.Data;
     4 import org.springframework.beans.factory.annotation.Value;
     5 import org.springframework.context.annotation.Configuration;
     6 
     7 /**
     8  * 配置文件包装类
     9  * @author cheng2839
    10  * @date 2018年11月16日
    11  */
    12 @Data
    13 @Configuration
    14 public class ConstantConfig {
    15 
    16     /////////////////// redis配置  ///////////////////
    17     @Value("${spring.redis.host}")
    18     private String redisHost;
    19 
    20     @Value("${spring.redis.port}")
    21     private int redisPort;
    22 
    23     @Value("${spring.redis.password}")
    24     private String redisPassword;
    25 
    26     @Value("${spring.redis.database}")
    27     private int redisDatabase;
    28 
    29 }

    创建配置文件application.properties如下:

     1 # REDIS配置
     2 spring.redis.database=0
     3 spring.redis.host=127.0.0.1
     4 spring.redis.port=6379
     5 spring.redis.password=
     6 spring.redis.pool.max-active=200
     7 spring.redis.pool.max-wait=10000
     8 spring.redis.pool.max-idle=50
     9 spring.redis.pool.min-idle=5
    10 spring.redis.timeout=10000

    最后,redis配置类RedisConfig如下:

      1 package com.cheng2839.config;
      2 
      3 import com.fasterxml.jackson.annotation.JsonAutoDetect;
      4 import com.fasterxml.jackson.annotation.PropertyAccessor;
      5 import com.fasterxml.jackson.databind.ObjectMapper;
      6 import org.slf4j.Logger;
      7 import org.slf4j.LoggerFactory;
      8 import org.springframework.context.annotation.Bean;
      9 import org.springframework.beans.factory.annotation.Autowired;
     10 import org.springframework.cache.annotation.CachingConfigurerSupport;
     11 import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
     12 import org.springframework.data.redis.core.RedisTemplate;
     13 import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
     14 import org.springframework.data.redis.serializer.StringRedisSerializer;
     15 import org.springframework.context.annotation.Configuration;
     16 
     17 import java.util.concurrent.TimeUnit;
     18 
     19 /**
     20  * Redis配置及基础方法实现封装类
     21  * @author cheng2839
     22  * @date 2018年11月16日
     23  */
     24 @Configuration
     25 public class RedisConfig extends CachingConfigurerSupport {
     26 
     27     private static final Logger logger = LoggerFactory.getLogger(RedisConfig.class);
     28 
     29     @Autowired
     30     private ConstantConfig config;
     31 
     32     private RedisTemplate<String, Object> redisTemplate;
     33 
     34     /**
     35      * 创建JedisConnectionFactory
     36      * @return
     37      * @author cheng2839
     38      * @date 2018年11月16日
     39      */
     40     @Bean(name = "factory")
     41     public JedisConnectionFactory createFactory() {
     42         JedisConnectionFactory factory = new JedisConnectionFactory();
     43         factory.setHostName(config.getRedisHost());
     44         factory.setPort(config.getRedisPort());
     45         factory.setPassword(config.getRedisPassword());
     46         factory.setDatabase(config.getRedisDatabase());
     47         return factory;
     48     }
     49 
     50     /**
     51      * 创建RedisTemplate
     52      * @param factory
     53      * @return
     54      */
     55     @Bean(name = "redisTemplate")
     56     public RedisTemplate<String, Object> createRedisTemplate(JedisConnectionFactory factory) {
     57         redisTemplate = new RedisTemplate<>();
     58         redisTemplate.setConnectionFactory(factory);
     59 
     60         //设置序列化/反序列化方式
     61         Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class);
     62         ObjectMapper mapper = new ObjectMapper();
     63         mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
     64         mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
     65         serializer.setObjectMapper(mapper);
     66 
     67         redisTemplate.setValueSerializer(serializer);
     68         redisTemplate.setKeySerializer(new StringRedisSerializer());
     69         redisTemplate.afterPropertiesSet();
     70         return redisTemplate;
     71     }
     72 
     73 
     74     //////////////////   下面为 Redis基础操作方法 可根据情况扩展  //////////////////
     75 
     76     /**
     77      * 添加一个key,无过期时间
     78      * @param key
     79      * @param value
     80      * @author cheng2839
     81      * @date 2018年11月16日
     82      */
     83     public void set(String key, Object value) {
     84         logger.info("[redis.set:({},{})]", key, value);
     85         redisTemplate.opsForValue().set(key, value);
     86     }
     87 
     88     /**
     89      * 添加一个key,并设置过期时间
     90      * @param key
     91      * @param value
     92      * @param time
     93      * @param timeUnit
     94      * @author cheng2839
     95      * @date 2018年11月16日
     96      */
     97     public void set(String key, Object value, long time, TimeUnit timeUnit) {
     98         logger.info("[redis.set:({},{})-({} {})]", key, value, time, timeUnit);
     99         redisTemplate.opsForValue().set(key, value, time, timeUnit);
    100     }
    101 
    102     /**
    103      * get redis value
    104      * @param key
    105      * @return
    106      * @author cheng2839
    107      * @date 2018年11月16日
    108      */
    109     public Object get(String key) {
    110         logger.info("[redis.get:({})]", key);
    111         return redisTemplate.opsForValue().get(key);
    112     }
    113 
    114     /**
    115      * 设置key的过期时间
    116      * @param key
    117      * @param time
    118      * @param timeUnit
    119      * @author cheng2839
    120      * @date 2018年11月16日
    121      */
    122     public void expire(String key, long time, TimeUnit timeUnit) {
    123         logger.info("[redis.expire:({})-({} {})]", key, time, timeUnit);
    124         redisTemplate.expire(key, time, timeUnit);
    125     }
    126 
    127     /**
    128      * 删除key
    129      * @param key
    130      * @author cheng2839
    131      * @date 2018年11月16日
    132      */
    133     public void delete(String key){
    134         logger.info("[redis.delete:({})]", key);
    135         redisTemplate.delete(key);
    136     }
    137 
    138     /**
    139      * 判断key是否存在
    140      * @param key
    141      * @return
    142      * @author cheng2839
    143      * @date 2018年11月16日
    144      */
    145     public boolean hasKey(String key) {
    146         logger.info("[redis.hasKey:({})]", key);
    147         return redisTemplate.hasKey(key);
    148     }
    149 
    150     //////////////////   上面为 Redis基础操作方法 可根据情况扩展  //////////////////
    151 
    152 }

    使用也很方便,我们创建一个RedisTest测试类来测试一下:

     1 package com.cheng2839.test;
     2 
     3 import org.springframework.beans.factory.annotation.Autowired;
     4 import com.cheng2839.config.RedisConfig;
     5 import org.slf4j.Logger;
     6 import org.slf4j.LoggerFactory;
     7 
     8 public class RedisTest {
     9 
    10     public Logger logger = LoggerFactory.getLogger(this.getClass());
    11 
    12     @Autowired
    13     private RedisConfig redisConfig;
    14 
    15     public static void main(String[] args) {
    16         String key = "cheng2839";
    17         redisConfig.set(key, "这是我的博客");
    18         Object val = redisConfig.get(key);
    19         logger.info("查询redis中的值:key:" + key + "	value:" + val);
    20 
    21         boolean hasKey = redisConfig.hasKey(key);
    22         logger.info("查询redis中key:" + key + ":" + hasKey);
    23 
    24         redisConfig.delete(key);
    25         val = redisConfig.get(key);
    26         logger.info("查询redis中的值:key:" + key + "	value:" + val);
    27     }
    28 
    29 }
     1 package com.cheng2839.test;
     2 
     3 import org.springframework.beans.factory.annotation.Autowired;
     4 import com.cheng2839.config.RedisConfig;
     5 
     6 public class RedisTest {
     7 
     8     @Autowired
     9     private RedisConfig redisConfig;
    10 
    11     public static void main(String[] args) {
    12         String key = "cheng2839";
    13         redisConfig.set(key, "这是我的博客");
    14         Object val = redisConfig.get(key);
    15         System.out.println("查询redis中的值:key:" + key + "	value:" + val);
    16 
    17         boolean hasKey = redisConfig.hasKey(key);
    18         System.out.println("查询redis中key:" + key + ":" + hasKey);
    19 
    20         redisConfig.delete(key);
    21         val = redisConfig.get(key);
    22         System.out.println("查询redis中的值:key:" + key + "	value:" + val);
    23     }
    2

    测试打印日志如下:

    2018-11-16 13:56:33.217 [redis.set:(cheng2839,这是我的博客)]
    2018-11-16 13:56:33.222 [redis.get:(cheng2839)]
    2018-11-16 13:56:33.225 查询redis中的值:key:cheng2839    value:这是我的博客
    2018-11-16 13:56:33.225 [redis.hasKey:(cheng2839)]
    2018-11-16 13:56:33.228 查询redis中key:cheng2839:true
    2018-11-16 13:56:33.228 [redis.delete:(cheng2839)]
    2018-11-16 13:56:33.230 [redis.get:(cheng2839)]
    2018-11-16 13:56:33.233 查询redis中的值:key:cheng2839    value:null

          后续给大家带来redis的安装、部署、配置;包括集群的设置等

    ____________________________特此,勉励____________________________
    本文作者cheng2839
    本文链接https://www.cnblogs.com/cheng2839
    关于博主:评论和私信会在第一时间回复。
    版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
    声援博主:如果您觉得文章对您有帮助,可以点击文章右下角【推荐】一下。您的鼓励是博主的最大动力!
  • 相关阅读:
    JS在线编辑器
    meta标签
    webstorm快捷键
    微信JS-SDK调用
    iOS -- UIApplication
    Xcode -- apple llvm 6.0 error错误如何解决
    C -- 字符串数组与字符串指针
    MAC -- 小技巧
    C语言 -- 折半查找小程序
    C -- 小程序
  • 原文地址:https://www.cnblogs.com/cheng2839/p/12604124.html
Copyright © 2020-2023  润新知