当前位置: 首页 > news >正文

SpringCache

目录

SpringCache

引入

自动配置

自定义配置

注解 

@Cacheable

@CacheEvict​​

sync = true


SpringCache

集成与管理缓存,它通过声明式注解和统一的 API,将缓存逻辑与业务逻辑解耦,支持多种缓存实现(如 Redis、Ehcache、Caffeine 等),并提供了灵活的配置选项。

引入

        <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-cache</artifactId></dependency>
@EnableCaching开启缓存

自动配置

CacheAutoConfiguration 依据缓存类型,自动配置缓存。
CacheConfigurations 映射 相应的缓存配置
    static {Map<CacheType, Class<?>> mappings = new EnumMap(CacheType.class);mappings.put(CacheType.GENERIC, GenericCacheConfiguration.class);mappings.put(CacheType.EHCACHE, EhCacheCacheConfiguration.class);mappings.put(CacheType.HAZELCAST, HazelcastCacheConfiguration.class);mappings.put(CacheType.INFINISPAN, InfinispanCacheConfiguration.class);mappings.put(CacheType.JCACHE, JCacheCacheConfiguration.class);mappings.put(CacheType.COUCHBASE, CouchbaseCacheConfiguration.class);mappings.put(CacheType.REDIS, RedisCacheConfiguration.class);mappings.put(CacheType.CAFFEINE, CaffeineCacheConfiguration.class);mappings.put(CacheType.SIMPLE, SimpleCacheConfiguration.class);mappings.put(CacheType.NONE, NoOpCacheConfiguration.class);MAPPINGS = Collections.unmodifiableMap(mappings);}
RedisCacheConfiguration 为每一个缓存"分区" 提供初始化,并返回Manager
    @Beanpublic RedisCacheManager cacheManager(RedisConnectionFactory redisConnectionFactory, ResourceLoader resourceLoader) {RedisCacheManager.RedisCacheManagerBuilder builder = RedisCacheManager.builder(redisConnectionFactory).cacheDefaults(this.determineConfiguration(resourceLoader.getClassLoader()));List<String> cacheNames = this.cacheProperties.getCacheNames();if (!cacheNames.isEmpty()) {builder.initialCacheNames(new LinkedHashSet(cacheNames));}return (RedisCacheManager)this.customizerInvoker.customize(builder.build());}
Manager为每一个分区进行默认配置defaultCacheConfiguration
        public RedisCacheManagerBuilder initialCacheNames(Set<String> cacheNames) {Assert.notNull(cacheNames, "CacheNames must not be null!");Map<String, RedisCacheConfiguration> cacheConfigMap = new LinkedHashMap(cacheNames.size());cacheNames.forEach((it) -> {RedisCacheConfiguration var10000 = (RedisCacheConfiguration)cacheConfigMap.put(it, this.defaultCacheConfiguration);});return this.withInitialCacheConfigurations(cacheConfigMap);}
redisCacheConfiguration 若为空,这采用默认配置
    private org.springframework.data.redis.cache.RedisCacheConfiguration determineConfiguration(ClassLoader classLoader) {if (this.redisCacheConfiguration != null) {return this.redisCacheConfiguration;} else {CacheProperties.Redis redisProperties = this.cacheProperties.getRedis();org.springframework.data.redis.cache.RedisCacheConfiguration config = org.springframework.data.redis.cache.RedisCacheConfiguration.defaultCacheConfig();config = config.serializeValuesWith(SerializationPair.fromSerializer(new JdkSerializationRedisSerializer(classLoader)));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;}}

自定义配置

容器中注入一个 RedisCacheConfiguration

@EnableCaching
@Configuration
public class MyCacheConfig {@Autowiredprivate CacheProperties cacheProperties;@BeanRedisCacheConfiguration redisCacheConfiguration(){RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();config = config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()));//Json序列化config = config.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericFastJsonRedisSerializer()));//使配置文件生效CacheProperties.Redis redisProperties = this.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;}
}
spring.cache.type=redis#缓存空值,防止缓存穿透
spring.cache.redis.cache-null-values=true
#spring.cache.redis.time-to-live=3600000
#spring.cache.redis.key-prefix=CACHE_
spring.cache.redis.use-key-prefix=true

注解 

@Cacheable

缓存方法返回值,若缓存命中则直接返回结果,否则执行方法并缓存结果。

键名 默认格式 缓存名::SimpleKey[param1, param2,...],支持 SpEL 表达式

@Cacheable(key = "#id")                 // 使用参数 id 作为键
@Cacheable(key = "#user.id")           // 使用对象属性作为键
@Cacheable(key = "#root.methodName")   // 使用方法名作为键[1,3](@ref)

默认使用jdk序列化机制,可在自定义配置中使用Json序列化器

@CacheEvict​​

清除缓存数据

sync = true

 同步锁,本地锁,仅@Cacheable支持

@Cacheable(cacheNames = "category",key = "#root.methodName",sync = true)

http://www.xdnf.cn/news/1176967.html

相关文章:

  • 双紫擒龙紫紫红黄安装使用攻略,2025通达信指标源码,擒龙追踪源码公式学习
  • 遨游三防平板|国产芯片鸿蒙系统单北斗三防平板,安全高效
  • 算法调试技巧
  • 《使用Qt Quick从零构建AI螺丝瑕疵检测系统》——4. 前后端联动:打通QML与C++的任督二脉
  • 【基础】go基础学习笔记
  • 极客大挑战2019-HTTP
  • 基于Odoo的微信小程序全栈开发探索分析
  • 探索复杂列表开发:从基础到高级的全面指南
  • SSE与Websocket有什么区别?
  • 如何在 conda 中删除环境
  • rust-结构体使用示例
  • Elasticsearch 的聚合(Aggregations)操作详解
  • 使用phpstudy极简快速安装mysql
  • Java 大视界 -- Java 大数据在智能家居能源管理与节能优化中的深度应用(361)
  • API安全监测工具:数字经济的免疫哨兵
  • 五、Vue项目开发流程
  • LeetCode 2563.统计公平数对的数目
  • Effective Python 第16条:用get处理字典缺失键,避免in与KeyError的陷阱
  • 【低空经济之无人集群】
  • runc源码解读(一)——runc create
  • C++右值引用与移动语义详解
  • QML 模型
  • git更新内核补丁完整指南
  • Android LiveData 全面解析:原理、使用与最佳实践
  • 【智能协同云图库】智能协同云图库第六弹:空间模块开发
  • 飞腾D3000麒麟信安系统下配置intel I210 MAC
  • Spring AI - 函数调用演示:AI算术运算助手
  • 复盘—MySQL触发器实现监听数据表值的变化,对其他数据表做更新
  • act_hi_taskinst表历史任务记录不同步,无数据
  • 边缘智能体:轻量化部署与离线运行