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

发布了308 篇原创文章 · 获赞 70 · 访问量 38万+

猜你喜欢

转载自blog.csdn.net/u012848709/article/details/105732747