Spring-IO-Caching 一


Spring Caching采用了一种透明的方式为应用提供缓存支持。它支持多种Provider(Generic、JCache、EhCache 2.x、Hazelcast、Infinispan、Couchbase、Redis、Caffeine、Cache2k、Simple),本文我们主要研究Redis Provider。

初始项目

使用spring初始化工具,初始化一个spring boot项目。

开启缓存 @EnableCaching

@EnableCaching
@SpringBootApplication
public class SpringStudyApplication {
	public static void main(String[] args) {
		SpringApplication.run(SpringStudyApplication.class, args);
	}
}

写一个测试方法

package com.pear.spring.study;

import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@RestController
@RequestMapping("cache")
public class CacheController {
    @GetMapping("test")
    @Cacheable(cacheNames = "cacheName", key = "'key'")
    public String cache() {
        System.out.println(new Date());
        return "hello cache";
    }
}

运行起来试试看,http://localhost:8080/cache/test
第一次访问,返回了 hello cache,控制台打印了时间
第二次访问,返回了 hello cache,控制台没有打印时间(缓存生效了)
还没有做任何配置,缓存就生效了。

缓存如何生效的,存在了哪里?

标记缓存方法的拦截

  1. @EnableCaching 的 mode 默认值为 AdviceMode.PROXY,并导入了CachingConfigurationSelector
  2. CachingConfigurationSelector继承了AdviceModeImportSelector,Spring加载导入对象时,会调用AdviceModeImportSelector.selectImports 获取关联导入项
  3. CachingConfigurationSelector根据AdviceMode.PROXY,返回了AutoProxyRegistrar、ProxyCachingConfiguration
  4. 重点看一下ProxyCachingConfiguration,在这个类中定义了CacheInterceptor的对象,主要用于拦截标记缓存的方法

缓存存储

经过调试发现,默认缓存是存储在org.springframework.cache.concurrent.ConcurrentMapCache中的,由SimpleCacheConfiguration进行初始化。
文章开始已经说过Spring Caching支持多种Provider,Simple是最后一个。为什么默认了Simple?这个要来从spring boot的自动装配来看了:
1. spring自动装载了CacheAutoConfiguration
2. CacheAutoConfiguration import 了 CacheConfigurationImportSelector
3. CacheConfigurationImportSelector 返回了 CacheType 包含的所有Privder:
CacheType.GENERIC, GenericCacheConfiguration 需要有任意的org.springframework.cache.Cache对象
CacheType.EHCACHE, EhCacheCacheConfiguration 需要其他组件
CacheType.HAZELCAST, HazelcastCacheConfiguration 需要其他组件
CacheType.INFINISPAN, InfinispanCacheConfiguration 需要其他组件
CacheType.JCACHE, JCacheCacheConfiguration 需要其他组件
CacheType.COUCHBASE, CouchbaseCacheConfiguration 需要其他组件
CacheType.REDIS, RedisCacheConfiguration 需要其他组件
CacheType.CAFFEINE, CaffeineCacheConfiguration 需要其他组件
CacheType.CACHE2K, Cache2kCacheConfiguration 需要其他组件
CacheType.SIMPLE, SimpleCacheConfiguration 不依赖任何对象,命中加载成功
CacheType.NONE, NoOpCacheConfiguration 已有CacheManager对象不再加载

总结

spring boot 使用默认缓存两步

  1. @EnableCaching
  2. 需要缓存的方法上加 @Cacheable

默认使用的缓存为:SimpleCacheConfiguration

本文使用的是spring-boot 2.7.18

  • 19
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值