springboot整合redis的步骤与技巧

springboot整合redis的步骤与技巧

  1. 添加依赖

         <!--默认是lettuce客户端-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-redis</artifactId>
            </dependency>
    
            <!-- redis依赖commons-pool 这个依赖一定要添加 -->
            <dependency>
                <groupId>org.apache.commons</groupId>
                <artifactId>commons-pool2</artifactId>
            </dependency>
    
            <!-- 这是Apache的工具类,主要用他的(对象转map)与map转对象的方法 -->
             <dependency>
                <groupId>commons-beanutils</groupId>
                <artifactId>commons-beanutils</artifactId>
                <version>1.9.4</version>
            </dependency>
    
  2. 配置类

    //有过时方法,可以重新找最新的
    import com.fasterxml.jackson.annotation.JsonAutoDetect;
    import com.fasterxml.jackson.annotation.PropertyAccessor;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import org.springframework.cache.CacheManager;
    import org.springframework.cache.annotation.CachingConfigurerSupport;
    import org.springframework.cache.interceptor.KeyGenerator;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.data.redis.cache.RedisCacheConfiguration;
    import org.springframework.data.redis.cache.RedisCacheManager;
    import org.springframework.data.redis.cache.RedisCacheWriter;
    import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
    import org.springframework.data.redis.serializer.StringRedisSerializer;
    import java.lang.reflect.Method;
    
    /**
     * @ClassName RedisConfig
     * @Description TODO
     * @Author shj
     * @Version 1.0
     */
    @Configuration
    public class RedisConfig extends CachingConfigurerSupport {
    
        /**
         * 自定义缓存key的生成策略。默认的生成策略是看不懂的(乱码内容) 通过Spring 的依赖注入特性进行自定义的配置注入并且此类是一个配置类可以更多程度的自定义配置
         *
         * @return
         */
        @Bean
        @Override
        public KeyGenerator keyGenerator() {
            return new KeyGenerator() {
                @Override
                public Object generate(Object target, Method method, Object... params) {
                    StringBuilder sb = new StringBuilder();
                    sb.append(target.getClass().getName());
                    sb.append(method.getName());
                    for (Object obj : params) {
                        sb.append(obj.toString());
                    }
                    return sb.toString();
                }
            };
        }
    
        /**
         * 缓存配置管理器
         */
        @Bean
        public CacheManager cacheManager(LettuceConnectionFactory factory) {
            //以锁写入的方式创建RedisCacheWriter对象
            RedisCacheWriter writer = RedisCacheWriter.lockingRedisCacheWriter(factory);
            //创建默认缓存配置对象
            RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
            RedisCacheManager cacheManager = new RedisCacheManager(writer, config);
            return cacheManager;
        }
    
        @Bean
        public RedisTemplate<String,Object> redisTemplate(LettuceConnectionFactory factory){
            RedisTemplate<String,Object> template = new RedisTemplate <>();
            template.setConnectionFactory(factory);
    
            Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
            ObjectMapper om = new ObjectMapper();
            om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
            om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
            jackson2JsonRedisSerializer.setObjectMapper(om);
    
            StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
    
            // 在使用注解@Bean返回RedisTemplate的时候,同时配置hashKey与hashValue的序列化方式。
            // key采用String的序列化方式
            template.setKeySerializer(stringRedisSerializer);
            // value序列化方式采用jackson
            template.setValueSerializer(jackson2JsonRedisSerializer);
    
            // hash的key也采用String的序列化方式
            template.setHashKeySerializer(stringRedisSerializer);
            // hash的value序列化方式采用jackson
            template.setHashValueSerializer(jackson2JsonRedisSerializer);
            template.afterPropertiesSet();
            return template;
        }
    }
    
  3. 使用与技巧

    1. 利用spring的自动注入,注入ValueOperations,相当于redisTemplate.opsForValue()并且自动转换类型,但是如果类型对应不上会报错

          //redis的封装的模板方法
        @Autowired
          private RedisTemplate<String, Object> redisTemplate;
      
        //注入redisTemplate,类型可以更改,k-v与redis对应.此时这里的String可以实现redis常用方法
          @Resource(name = "redisTemplate")
          private ValueOperations<String, String> string;
      
          @Resource(name = "redisTemplate")
          private ValueOperations<String, Integer> integer;
      
          @Resource(name = "redisTemplate")
          private ValueOperations<String, Verification> obj;
      
    2. ValueOperations(与redisTemplate.opsForValue的类似)的方法

      1. increment(K key, double delta) 以增量的方式将double值存储在变量中。

      2. setIfAbsent(K key, V value) 如果键不存在则新增,存在则不改变已经有的值。

      3. set(K key, V value, long timeout, TimeUnit unit) 设置变量值的过期时间。

      4. set(K key, V value, long offset) 覆盖从指定位置开始的值。

      5. multiSet(Map<? extends K,? extends V> map) 设置map集合到redis。

      6. multiGet(Collection<K> keys) 根据集合取出对应的value值。

      7. multiSetIfAbsent(Map<? extends K,? extends V> map) 如果对应的map集合名称不存在,则添加;如果存在则不做修改。

      8. append(K key, String value) 在原有的值基础上新增字符串到末尾。

    3. 注入HashOperations

      1. 优点:存入的为对象,取值时可以根据 对象名+变量名 直接从redis中取出

      2. 注意:如果通过Beanutils将对象变为map时会附加一个class的变量

      3.     @Autowired
            private RedisTemplate<String, Object> redisTemplate; 
        
            //直接注入  与redisTemplate.opsForHash类似
            @Resource(name = "redisTemplate")
            private HashOperations<String, String,String> hash;
        
      4.  /**
             * 通过Beanutils的BeanMap方法直接转换
             */
            public Boolean set() {
                Verification verification = new Verification();
                verification.setNum(true);
                verification.setRandom("shj");
                Map beanMap = new BeanMap(verification);
                hash.putAll("person2",beanMap);
                return true;
            }
        
      5. public String getString() {
            //直接拿到对象中的属性
            String s = hash.get("person2", "class");
            //获取整个对象
            Map<String, String> person2 = hash.entries("person2");
            Verification verification = new Verification();
            try {
                //使用Apache的方法进行   map转对象
                org.apache.commons.beanutils.BeanUtils.populate(verification, person2);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
            System.out.println(verification);
            return s;
        }
        
    4. 通过注入的方式还能注入其他许多的XXXOperations 的类

      private ListOperations
      private SetOperations
      private ZSetOperations
      ....
      
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。