栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

缓存Cache

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

缓存Cache

第一步:
引入依赖   
    org.springframework.boot
    spring-boot-starter-data-redis

        org.springframework.boot
        spring-boot-starter-cache
第二步:开启缓存        @EnableCaching 第三步:配置   spring.cache.type=redis #spring.cache.cache-names=qq,毫秒为单位
spring.cache.redis.time-to-live=3600000 #如果指定了前缀就用我们指定的前缀,如果没有就默认使用缓存的名字作为前缀#spring.cache.redis.key-prefix=CACHE_
spring.cache.redis.use-key-prefix=true #是否缓存空值,防止缓存穿透
spring.cache.redis.cache-null-values=true

第四步:使用注解
@Cacheable(value = {"category"}, key = "#root.method.name", sync = true)


        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;
    }

}
* 4、Spring-Cache的不足之处:
 * 1)、读模式
 * 缓存穿透:查询一个null数据。解决方案:缓存空数据
 * 缓存击穿:大量并发进来同时查询一个正好过期的数据。解决方案:加锁 ? 默认是无加锁的;使用sync = true来解决击穿问题
 * 缓存雪崩:大量的key同时过期。解决:加随机时间。加上过期时间
 * 2)、写模式:(缓存与数据库一致)
 * 1)、读写加锁。
 * 2)、引入Canal,感知到MySQL的更新去更新Redis
 * 3)、读多写多,直接去数据库查询就行
 * 总结:
 * 常规数据(读多写少,即时性,一致性要求不高的数据,完全可以使用Spring-Cache):写模式(只要缓存的数据有过期时间就足够了)
 * 特殊数据:特殊设计
 * 

* 原理: * CacheManager(RedisCacheManager)->Cache(RedisCache)->Cache负责缓存的读写 * * @return */

@CacheEvict触发将缓存数据删除操作(失效模式)

 

@CacheEvic(value = {"category"}, key = "#root.method.name")

//allEntries =true 删除catagory区域所有缓存数据
@CacheEvict(value = {"catagory"},allEntries = true)

 @CachePut不影响方法执行更新缓存(双写模式)
@Caching组合多个操作

@Caching(evict={
   @CacheEvic(value = {"category"}, key = "#root.method.name"),
   @CacheEvic(value = {"category"}, key = "#root.method.name"))
}

​​​​​@CacheConfig在类级别共享缓存的相同配置

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/295003.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号