springbootCache整合redisTemplate/redisson

記錄下整合的過程

step1

pom引用

 <dependency>
            <groupId>org.springframework.session</groupId>
            <artifactId>spring-session-data-redis</artifactId>
</dependency>

<!--如果需要redisson則需要引入-->
 <dependency>
            <groupId>org.redisson</groupId>
            <artifactId>redisson</artifactId>
            <version>3.8.0</version>
</dependency>

step2

寫配置類(名字任意)
CacheConfiguration

package com.jike.goldenpig.configration;

import org.redisson.api.RedissonClient;
import org.redisson.spring.cache.CacheConfig;
import org.redisson.spring.cache.RedissonSpringCacheManager;
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.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 *
 *
 * @author azhang.wang [email protected]
 * @version CacheConfiguration.java, v 0.1 2017-02-21 10:38 AM Exp $
 */
@Configuration
public class CacheConfiguration extends CachingConfigurerSupport {

    public static final String DEFALUT_KEY="DEFALUT_KEY";

    @Bean
    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate template = new RedisTemplate();

        template.setConnectionFactory(factory);

        RedisSerializer keySerializer = new StringRedisSerializer();

        template.setKeySerializer(keySerializer);
        template.setHashKeySerializer(keySerializer);

        GenericJackson2JsonRedisSerializer jsonSerializer = new GenericJackson2JsonRedisSerializer();

        // 設置內容序列化類
        template.setValueSerializer(jsonSerializer);

        template.afterPropertiesSet();

        return template;
    }
    @Bean
    public CacheManager cacheManager(RedisTemplate redisTemplate) {
        RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
        //想要的一個過期時間集合,如果在集合內則會使用集合設定的過期時間過期
        Map<String, Long> expires = new HashMap<>();
        //設置特定namespace的過期時間,優雅點可以抽出公共的constants,這裏爲了演示直接寫名稱
        expires.put("people", 20L);
       //自定義一個默認的key,默認時間爲60*60秒
        expires.put(DEFALUT_KEY, 60*60L);

        // 設置超時
        cacheManager.setExpires(expires);

        // 其他沒有在expires中的namespace,設置的默認過期時間
        cacheManager.setDefaultExpiration(60 * 60);

        return cacheManager;
    }

    @Bean
    CacheManager cacheManager(RedissonClient redissonClient) {
        Map<String, CacheConfig> config = new HashMap<>(16);
        // create "testMap" cache with ttl = 24 minutes and maxIdleTime = 12 minutes
        config.put("user", new CacheConfig(20*1000, 12 * 60 * 1000));
        config.put("people", new CacheConfig(30*1000, 12 * 60 * 1000));
        return new RedissonSpringCacheManager(redissonClient, config);

    }
    @Override
    public KeyGenerator keyGenerator() {
        return new KeyGenerator() {
            @Override
            public Object generate(Object target, Method method, Object... params) {
                StringBuilder sb = new StringBuilder();
                sb.append("CacheKey:");
                sb.append(target.getClass().getSimpleName());
                sb.append('.').append(method.getName()).append(":");

                // 這裏需要注意,參數太多的話考慮使用其他拼接方式
                for (Object obj : params) {
                    if (obj != null) {
                        sb.append(obj.toString());
                        sb.append(".");
                    }
                }
                return sb.toString();
            }
        };
    }
}

以上 cacheManager 任意選擇一個開啓就好了。
可以看到,不管哪種方式,給容器一個CacheManager即可

step3

使用方式

   int i = 0;
    @RequestMapping(value = "cache")
    @ResponseBody
    @Cacheable("people")
    public int cache(String a,String b) {
        i++;
        return i;
    }
    @RequestMapping(value = "cache2")
    @ResponseBody
    @Cacheable("user")
    public int cache2(String a,String b) {
        i++;
        return i;
    }
    @RequestMapping(value = "index")
    @Cacheable(CacheConfiguration.DEFALUT_KEY)
    public String index(ModelAndView mv) {
        mv.addObject("name", "rose");
        mv.setViewName("index");
        return "index";
    }

這裏直接在控制層添加了,大家自己玩吧。

這裏說下,使用redission和RedisTemplate的差別很小,但是他們保存在redis中的key是不一樣的,原因是他們的失效機制不一樣
redission的會生成以下幾個key



redisson使用的是持久化的key,同時綁定在自身的定時任務中,時間到了就會觸發剔除動作,從而達到過期的效果
RedisTemplate則是直接生成key,



這是跟redisson不同的地方,同時給他設定失效時間,但是會生成一個命名空間對應的key,來記錄所有生成的記錄,這個key也會失效,但是失效時間是循環的,目前還不知道爲什麼這樣做,只能看到便於統計

對比兩者的結構,redisson使用的方式佔用的redis中key的數量會少很多,由此帶來一些便利,比如刪除

擴展可以參考這篇文章
Spring Boot緩存實戰 Redis 設置有效時間和自動刷新緩存,時間支持在配置文件中配置

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章