springboot redis緩存學習整理

楔子

springboot redis緩存 學習筆記,希望不要誤導人

整合pom

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.2.6.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.60</version>
</dependency>

配置 properties

配置

spring.redis.host=127.0.0.1
spring.redis.port=6379

## 緩存
################################ 緩存
spring.cache.type=redis
## 緩存時間,以毫秒爲單位
spring.cache.redis.time-to-live=7200000
## 緩存前綴|如果指定了 使用指定的,如果沒有指定,more使用 名字作爲前綴
#spring.cache.redis.key-prefix=CACHE_
## 不指定 前綴,可以直接使用自定義 分區
spring.cache.redis.use-key-prefix=true
## 是否緩存空值|防止 緩存穿透
spring.cache.redis.cache-null-values=true
################################ 緩存|end

註解開啓

自定義配置,使用 JSON作爲序列化

/**
 * 2020年4月23日19:44:49
 * 1 引入依賴
 * 2 配置 CacheAutoConfiguration|CacheProperties 配置了可以配置的屬性
 * CacheConfigurationImportSelector 選擇器 org.springframework.boot.autoconfigure.cache.CacheConfigurations#MAPPINGS
 * RedisCacheConfiguration
 * <span/> (1) 自動配置  CacheAutoConfiguration 會導入 RedisCacheConfiguration。自動配置了 緩存管理器RedisCacheManager
 * org.springframework.boot.autoconfigure.cache.RedisCacheConfiguration#createConfiguration(org.springframework.boot.autoconfigure.cache.CacheProperties, java.lang.ClassLoader)
 * <span/>(2)
 * 3 測試使用緩存
 *
 * @Cacheable//觸發將數據保存到緩存的操作
 * @CacheEvict//觸發將數據從緩存刪除的操作
 * @CachePut//不影響方法執行更新緩存
 * @Caching//組合以上多個操作
 * @CacheConfig//在類級別共享 緩存相同配置
 * 4 開啓緩存|@EnableCaching
 */

@EnableCaching//開啓緩存
@Configuration
@EnableConfigurationProperties(CacheProperties.class)
public class RedisCacheConfig {

    /**
     * redis序列化 使用JSON
     * https://github.com/alibaba/fastjson/issues/2780
     */
    @Bean
    public RedisCacheConfiguration redisCacheConfiguration(CacheProperties cacheProperties) {
        RedisCacheConfiguration config = org.springframework.data.redis.cache.RedisCacheConfiguration.defaultCacheConfig();
        config = config.serializeKeysWith(
                RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()));
        config = config.serializeValuesWith(
                RedisSerializationContext.SerializationPair.fromSerializer(new GenericFastJsonRedisSerializer()));//GenericFastJsonRedisSerializer|GenericJackson2JsonRedisSerializer


        //String ttlStr = environment.getProperty("spring.cache.redis.time-to-live");
        //config = config.entryTtl(Duration.ofSeconds(3600));

        CacheProperties.Redis redisProperties = cacheProperties.getRedis();
        if (redisProperties.getTimeToLive() != null) {
            config = config.entryTtl(redisProperties.getTimeToLive());
        }
        if (redisProperties.getKeyPrefix() != null) {
            config = config.prefixKeysWith(redisProperties.getKeyPrefix());
        }
        if (!redisProperties.isCacheNullValues()) {
            config = config.disableCachingNullValues();
        }
        if (!redisProperties.isUseKeyPrefix()) {
            config = config.disableKeyPrefix();
        }
        return config;
    }
}


使用

/**
 * 每一個緩存數據都來指定要放到哪個名字的緩衝【指定緩存分區】
 * Cacheable({"cahce:menu", "mu"})//代表 當前方法的結果需要緩存,如果緩存中有,方法不調用,如果緩存中沒有,查詢後彷如緩存
 * <br>
 * <p>
 * 3默認行爲
 * 3.1 如果有,方法不用調用
 * 3.2 key默認自動生成 ,緩存名字::SimpleKey []
 * 3.3 緩存value 默認jdk序列化 機制
 * 3.4 默認過期時間 -1
 * <p>
 * 4 自定義
 * 4.1 指定生成的緩存使用key:key屬性 指定,接受一個SpEL ,如果要用字符串,需要單引號
 * 4.2 緩存時間|配置文件spring.cache.redis.time-to-live
 * 4.3 指定JSON格式
 */
@Cacheable(value = {"cahce:menu", "mu"}, key = "'sysMenu'")//代表 當前方法的結果需要緩存,如果緩存中有,方法不調用,如果緩存中沒有,查詢後彷如緩存
@Override
public List<MenuStream> getAllwithJ8Stream() {
    log.info("menu with java8stream  by  mysql db");
    // 使用java8 stream 封裝父子關係,來展示 ztree 標準JSON格式
    List<MenuStream> queryForList = jtemplate.query("select id,pId ,name,url,icon from t_menu", new BeanPropertyRowMapper(MenuStream.class));

    // 獲取取根節點
    List<MenuStream> collect = queryForList.stream().filter((menu) -> {
        return menu.getPid() == null;
    }).map((menu) -> {
        menu.setChildren(getChildren(menu, queryForList));
        return menu;
    }).sorted((m1, m2) -> {
        return m1.getId() - m2.getId();
    }).collect(Collectors.toList());
    System.out.println(collect);
    return collect;
}

/**
 * 清除緩存
 */
//1 @CacheEvict(value = {"cahce:menu", "mu"}, key = "'sysMenu'")
/* 2 @Caching(evict = {
        @CacheEvict(value = "cahce:menu", key = "'sysMenu'"),
        @CacheEvict(value = "mu", key = "'sysMenu'")
})*/
@CacheEvict(value = "cahce:menu", allEntries = true)//cahce:menu::sysMenu|刪除 指定分區下的 緩存,不
//@CachePut//雙寫模式
@Override
@Transactional
public void menuDelcache() {
    log.info("menuDelcache");
}

代碼gitee

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