SpringCache源码解析(一)

news2024/9/22 21:15:05

一、springCache如何实现自动装配

SpringBoot 确实是通过 spring.factories 文件实现自动配置的。Spring Cache 也是遵循这一机制来实现自动装配的。

具体来说,Spring Cache 的自动装配是通过 org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration 这个类来实现的。这个类位于 spring-boot-autoconfigure 包下。

在 spring-boot-autoconfigure 包的 META-INF/spring.factories 文件中,可以找到 CacheAutoConfiguration 类的配置:
在这里插入图片描述

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration

二、CacheAutoConfiguration

@Configuration
@ConditionalOnClass(CacheManager.class)
@ConditionalOnBean(CacheAspectSupport.class)
@ConditionalOnMissingBean(value = CacheManager.class, name = "cacheResolver")
@EnableConfigurationProperties(CacheProperties.class)
@AutoConfigureAfter({ CouchbaseAutoConfiguration.class, HazelcastAutoConfiguration.class,
		HibernateJpaAutoConfiguration.class, RedisAutoConfiguration.class })
@Import(CacheConfigurationImportSelector.class)
public class CacheAutoConfiguration {

 /**
     * 创建CacheManagerCustomizers Bean
     * XxxCacheConfiguration中创建CacheManager时会用来装饰CacheManager
     */
	@Bean
	@ConditionalOnMissingBean
	public CacheManagerCustomizers cacheManagerCustomizers(ObjectProvider<CacheManagerCustomizer<?>> customizers) {
		return new CacheManagerCustomizers(customizers.orderedStream().collect(Collectors.toList()));
	}

/**
     * 创建CacheManagerValidator Bean
     * 实现了InitializingBean,在afterPropertiesSet方法中校验CacheManager
     */
	@Bean
	public CacheManagerValidator cacheAutoConfigurationValidator(CacheProperties cacheProperties,
			ObjectProvider<CacheManager> cacheManager) {
		return new CacheManagerValidator(cacheProperties, cacheManager);
	}

 /**
     * 后置处理器
     * 内部类,动态声明EntityManagerFactory实例需要依赖"cacheManager"实例
     */
	@Configuration
	@ConditionalOnClass(LocalContainerEntityManagerFactoryBean.class)
	@ConditionalOnBean(AbstractEntityManagerFactoryBean.class)
	protected static class CacheManagerJpaDependencyConfiguration extends EntityManagerFactoryDependsOnPostProcessor {

		public CacheManagerJpaDependencyConfiguration() {
			super("cacheManager");
		}

	}

	/**
     * 缓存管理器校验器
     * 内部类,实现了InitializingBean接口,实现afterPropertiesSet用于校验缓存管理器
     */
	static class CacheManagerValidator implements InitializingBean {

		private final CacheProperties cacheProperties;

		private final ObjectProvider<CacheManager> cacheManager;

		CacheManagerValidator(CacheProperties cacheProperties, ObjectProvider<CacheManager> cacheManager) {
			this.cacheProperties = cacheProperties;
			this.cacheManager = cacheManager;
		}

 /**
         * 当依赖注入后处理
         */
		@Override
		public void afterPropertiesSet() {
			Assert.notNull(this.cacheManager.getIfAvailable(),
					() -> "No cache manager could " + "be auto-configured, check your configuration (caching "
							+ "type is '" + this.cacheProperties.getType() + "')");
		}

	}

	/**
     * 缓存配置导入选择器
     */
	static class CacheConfigurationImportSelector implements ImportSelector {

		@Override
		public String[] selectImports(AnnotationMetadata importingClassMetadata) {
			CacheType[] types = CacheType.values();
			String[] imports = new String[types.length];
			for (int i = 0; i < types.length; i++) {
				imports[i] = CacheConfigurations.getConfigurationClass(types[i]);
			}
			return imports;
		}

	}

}

借助Conditional机制实现自动配置条件:

  1. CacheManager.class在类路径上存在;
  2. CacheAspectSupport实例存在(即CacheInterceptor);
  3. CacheManager实例不存在,且cacheResolver Bean不存在;
    当满足以上要求时,就会触发SpringCache的自动配置逻辑,CacheAutoConfiguration会引入其它的Bean,具体如下:
  4. 通过@EnableConfigurationProperties使CacheProperties生效;
  5. 借助Import机制导入内部类:CacheConfigurationImportSelector和CacheManagerEntityManagerFactoryDependsOnPostProcessor;
  6. 创建了CacheManagerCustomizers、CacheManagerValidator Bean;

2.1 关于的一些疑问

关于@ConditionalOnClass,我有一个疑问:

  • value值是类名,如果类找不到,会不会编译报错;
    ——会! 那value有什么意义?只要能编译过的,肯定都存在。
    ——@ConditionalOnClass注解之前一直让我感到困惑,类存不存在,编译器就会体现出来,还要这个注解干嘛?后来想了很久,感觉java语法并不是一定要寄生在idea上,所以语法上限制和工具上限制,这是两码事,理论上就应该彼此都要去做。

@ConditionalOnClass还可以用name属性:

@ConditionalOnClass(name="com.xxx.Component2")

可以看下这篇文章:
SpringBoot中的@ConditionOnClass注解

2.2 CacheProperties

// 接收以"spring.cache"为前缀的配置参数
@ConfigurationProperties(prefix = "spring.cache")
public class CacheProperties {

    // 缓存实现类型
    // 未指定,则由环境自动检测,从CacheConfigurations.MAPPINGS自上而下加载XxxCacheConfiguration
    // 加载成功则检测到缓存实现类型
    private CacheType type;

    // 缓存名称集合
    // 通常,该参数配置了则不再动态创建缓存
    private List<String> cacheNames = new ArrayList<>();

    private final Caffeine caffeine = new Caffeine();

    private final Couchbase couchbase = new Couchbase();

    private final EhCache ehcache = new EhCache();

    private final Infinispan infinispan = new Infinispan();

    private final JCache jcache = new JCache();

    private final Redis redis = new Redis();


    // getter and setter
    ...

    /**
     * Caffeine的缓存配置参数
     */
    public static class Caffeine {
        ...
    }

    /**
     * Couchbase的缓存配置参数
     */
    public static class Couchbase {
        ...
    }

    /**
     * EhCache的缓存配置参数
     */
    public static class EhCache {
        ...
    }

    /**
     * Infinispan的缓存配置参数
     */
    public static class Infinispan {
        ...
    }

    /**
     * JCache的缓存配置参数
     */
    public static class JCache {
        ...
    }

    /**
     * Redis的缓存配置参数
     */
    public static class Redis {

        // 过期时间,默认永不过期
        private Duration timeToLive;

        // 支持缓存空值标识,默认支持
        private boolean cacheNullValues = true;

        // 缓存KEY前缀
        private String keyPrefix;

        // 使用缓存KEY前缀标识,默认使用
        private boolean useKeyPrefix = true;

        // 启用缓存统计标识
        private boolean enableStatistics;

        // getter and setter
        ...
    }
}

2.3 CacheConfigurationImportSelector

CacheAutoConfiguration的静态内部类,实现了ImportSelector接口的selectImports方法,导入Cache配置类;

/**
 * 挑选出CacheType对应的配置类
 */
@Override
public String[] selectImports(AnnotationMetadata importingClassMetadata) {
    CacheType[] types = CacheType.values();
    String[] imports = new String[types.length];
    // 遍历CacheType
    for (int i = 0; i < types.length; i++) {
        // 获取CacheType的配置类
        imports[i] = CacheConfigurations.getConfigurationClass(types[i]);
    }
    return imports;
}

CacheConfigurationImportSelector,把所有缓存的配置类拿出来,加入到spring中被加载。

有的开发者可能就会问:
为什么要重载所有的配置类?而不是配置了哪种缓存类型就加载哪种缓存类型?
——这里只是加载所有的配置类,比如Redis,只是加载RedisCacheConfiguration.class配置类,后续会根据条件判断具体加载到哪个配置,如下图:
在这里插入图片描述

2.4 CacheConfigurations

维护了CacheType和XxxCacheConfiguration配置类的映射关系;

/**
 * CacheType和配置类的映射关系集合
 * 无任何配置条件下,从上而下,默认生效为SimpleCacheConfiguration
 */
static {
    Map<CacheType, String> mappings = new EnumMap<>(CacheType.class);
    mappings.put(CacheType.GENERIC, GenericCacheConfiguration.class.getName());
    mappings.put(CacheType.EHCACHE, EhCacheCacheConfiguration.class.getName());
    mappings.put(CacheType.HAZELCAST, HazelcastCacheConfiguration.class.getName());
    mappings.put(CacheType.INFINISPAN, InfinispanCacheConfiguration.class.getName());
    mappings.put(CacheType.JCACHE, JCacheCacheConfiguration.class.getName());
    mappings.put(CacheType.COUCHBASE, CouchbaseCacheConfiguration.class.getName());
    mappings.put(CacheType.REDIS, RedisCacheConfiguration.class.getName());
    mappings.put(CacheType.CAFFEINE, CaffeineCacheConfiguration.class.getName());
    mappings.put(CacheType.SIMPLE, SimpleCacheConfiguration.class.getName());
    mappings.put(CacheType.NONE, NoOpCacheConfiguration.class.getName());
    MAPPINGS = Collections.unmodifiableMap(mappings);
}

/**
 * 根据CacheType获取配置类
 */
static String getConfigurationClass(CacheType cacheType) {
    String configurationClassName = MAPPINGS.get(cacheType);
    Assert.state(configurationClassName != null, () -> "Unknown cache type " + cacheType);
    return configurationClassName;
}

/**
 * 根据配置类获取CacheType
 */
static CacheType getType(String configurationClassName) {
    for (Map.Entry<CacheType, String> entry : MAPPINGS.entrySet()) {
        if (entry.getValue().equals(configurationClassName)) {
            return entry.getKey();
        }
    }
    throw new IllegalStateException("Unknown configuration class " + configurationClassName);
}

2.5 CacheType

缓存类型的枚举,按照优先级定义;

GENERIC     // Generic caching using 'Cache' beans from the context.
JCACHE      // JCache (JSR-107) backed caching.
EHCACHE     // EhCache backed caching.
HAZELCAST   // Hazelcast backed caching.
INFINISPAN  // Infinispan backed caching.
COUCHBASE   // Couchbase backed caching.
REDIS       // Redis backed caching.
CAFFEINE    // Caffeine backed caching.
SIMPLE      // Simple in-memory caching.
NONE        // No caching.

2.4 CacheCondition

它是所有缓存配置使用的通用配置条件;

2.4.1 准备工作

介绍之前先看一些CacheCondition类使用的地方,可以看到是各种缓存类型类型的配置类使用了它。
在这里插入图片描述

@Conditional注解的作用是什么?
——请看这篇文章@Conditional 注解有什么用?

说穿了,就是根据注解参数Condition实现类(这里是CacheCondition类)的matches方法返回,来判断是否加载这个配置类。

2.4.2 CacheCondition核心代码

/**
 * 匹配逻辑
 */
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
    String sourceClass = "";
    if (metadata instanceof ClassMetadata) {
        sourceClass = ((ClassMetadata) metadata).getClassName();
    }
    ConditionMessage.Builder message = ConditionMessage.forCondition("Cache", sourceClass);
    Environment environment = context.getEnvironment();
    try {
        // 获取配置文件中指定的CacheType
        BindResult<CacheType> specified = Binder.get(environment).bind("spring.cache.type", CacheType.class);
        if (!specified.isBound()) {
            // 不存在则根据CacheConfiguration.mappings自上而下匹配合适的CacheConfiguration
            return ConditionOutcome.match(message.because("automatic cache type"));
        }
        CacheType required = CacheConfigurations.getType(((AnnotationMetadata) metadata).getClassName());
        // 存在则比较CacheType是否一致
        if (specified.get() == required) {
            return ConditionOutcome.match(message.because(specified.get() + " cache type"));
        }
    }
    catch (BindException ex) {
    }
    return ConditionOutcome.noMatch(message.because("unknown cache type"));
}

三、常见的CacheConfiguration

3.1 RedisCacheConfiguration

它是Redis缓存配置;

// Bean方法不被代理
@Configuration(proxyBeanMethods = false)
// RedisConnectionFactory在类路径上存在
@ConditionalOnClass(RedisConnectionFactory.class)
// 在RedisAutoConfiguration之后自动配置
@AutoConfigureAfter(RedisAutoConfiguration.class)
// RedisConnectionFactory实例存在
@ConditionalOnBean(RedisConnectionFactory.class)
// CacheManager实例不存在
@ConditionalOnMissingBean(CacheManager.class)
// 根据CacheCondition选择导入
@Conditional(CacheCondition.class)
class RedisCacheConfiguration {

    /**
     * 创建RedisCacheManager
     */
    @Bean
    RedisCacheManager cacheManager(CacheProperties cacheProperties, CacheManagerCustomizers cacheManagerCustomizers,
            ObjectProvider<org.springframework.data.redis.cache.RedisCacheConfiguration> redisCacheConfiguration,
            ObjectProvider<RedisCacheManagerBuilderCustomizer> redisCacheManagerBuilderCustomizers,
            RedisConnectionFactory redisConnectionFactory, ResourceLoader resourceLoader) {
        // 使用RedisCachemanager
        RedisCacheManagerBuilder builder = RedisCacheManager.builder(redisConnectionFactory).cacheDefaults(
                determineConfiguration(cacheProperties, redisCacheConfiguration, resourceLoader.getClassLoader()));
        List<String> cacheNames = cacheProperties.getCacheNames();
        if (!cacheNames.isEmpty()) {
            // 设置CacheProperties配置的值
            builder.initialCacheNames(new LinkedHashSet<>(cacheNames));
        }
        if (cacheProperties.getRedis().isEnableStatistics()) {
            // 设置CacheProperties配置的值
            builder.enableStatistics();
        }
        // 装饰redisCacheManagerBuilder
        redisCacheManagerBuilderCustomizers.orderedStream().forEach((customizer) -> customizer.customize(builder));
        // 装饰redisCacheManager
        return cacheManagerCustomizers.customize(builder.build());
    }

    /**
     * 如果redisCacheConfiguration不存在则使用默认值
     */
    private org.springframework.data.redis.cache.RedisCacheConfiguration determineConfiguration(
            CacheProperties cacheProperties,
            ObjectProvider<org.springframework.data.redis.cache.RedisCacheConfiguration> redisCacheConfiguration,
            ClassLoader classLoader) {
        return redisCacheConfiguration.getIfAvailable(() -> createConfiguration(cacheProperties, classLoader));
    }

    /**
     * 根据CacheProperties创建默认RedisCacheConfigutation
     */
    private org.springframework.data.redis.cache.RedisCacheConfiguration createConfiguration(
            CacheProperties cacheProperties, ClassLoader classLoader) {
        Redis redisProperties = cacheProperties.getRedis();
        org.springframework.data.redis.cache.RedisCacheConfiguration config =     org.springframework.data.redis.cache.RedisCacheConfiguration
                .defaultCacheConfig();
        config = config.serializeValuesWith(
                SerializationPair.fromSerializer(new JdkSerializationRedisSerializer(classLoader)));

        // 优先使用CacheProperties的值,若存在的话
        if (redisProperties.getTimeToLive() != null) {
            config = config.entryTtl(redisProperties.getTimeToLive());
        }
        if (redisProperties.getKeyPrefix() != null) {
            config = config.prefixCacheNameWith(redisProperties.getKeyPrefix());
        }
        if (!redisProperties.isCacheNullValues()) {
            config = config.disableCachingNullValues();
        }
        if (!redisProperties.isUseKeyPrefix()) {
            config = config.disableKeyPrefix();
        }
        return config;
    }
}

3.2 SimpleCacheConfiguration

// Bean方法不被代理
@Configuration(proxyBeanMethods = false)
// 不存在CacheManager实例
@ConditionalOnMissingBean(CacheManager.class)
// 根据CacheCondition选择导入
@Conditional(CacheCondition.class)
class SimpleCacheConfiguration {

    /**
     * 创建CacheManager
     */
    @Bean
    ConcurrentMapCacheManager cacheManager(CacheProperties cacheProperties,
            CacheManagerCustomizers cacheManagerCustomizers) {
        // 使用ConcurrentMapCacheManager
        ConcurrentMapCacheManager cacheManager = new ConcurrentMapCacheManager();
        List<String> cacheNames = cacheProperties.getCacheNames();
        // 如果CacheProperties配置了cacheNames,则使用
        if (!cacheNames.isEmpty()) {
            // 配置了cacheNames,则不支持动态创建缓存了
            cacheManager.setCacheNames(cacheNames);
        }
        // 装饰ConcurrentMapCacheManager
        return cacheManagerCustomizers.customize(cacheManager);
    }
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2068688.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

文件树控件开发

文件树控件和获取驱动信息功能 然后添加上查看文件信息的按钮 双击这个按钮添加上如下代码 void CRemoteClientDlg::OnBnClickedBtnFileinfo() {int ret SendCommandPacket(1);if (ret -1) {AfxMessageBox(_T("命令处理失败!!!"));return;}ClientSocket* pClient…

c++每日练习记录5-(链表的结尾指向nullptr)

解题方法&#xff1a;双指针法 ListNode *partition(ListNode *head, int x){ListNode *head1 new ListNode(0);ListNode *head2 head1;ListNode *head3 new ListNode(0);ListNode *head4 head3;while (head! nullptr){if (head->val < x){head1->next head;head…

成品CNC外壳的巧妙使用

有些时候10块买一个CNC外壳&#xff0c;钻个孔&#xff0c;比单独的3D打印更能提升板子的档次感&#xff1a; 这个CNC是真的好看&#xff0c;再加上3D打印辅助设计&#xff0c;堪称精美&#xff1a;

k8s安装Metabase开源报表系统

metabase是什么&#xff1f; metabase是一款开源的简易但强大同时又无缝兼容大数据和传统数据库的分析工具&#xff0c;帮助公司每一个人对企业数据的学习挖掘&#xff0c;进而达到更好的数据化运营和决策。 Metabase is a simple and powerful analytics tool which lets anyo…

热血传奇1.76版本完美仿官单机版安装教程+GM工具+无需虚拟机

今天给大家带来一款单机游戏的架设&#xff1a;热血传奇1.76版本完美仿官。 另外&#xff1a;本人承接各种游戏架设&#xff08;单机联网&#xff09; 本人为了学习和研究软件内含的设计思想和原理&#xff0c;带了架设教程仅供娱乐。 教程是本人亲自搭建成功的&#xff0c;…

软件上显示“mfc140.dll丢失”错误信息?那么mfc140.dll丢失该如何修复

mfc140.dll是 Microsoft Foundation Class (MFC) 库的一部分&#xff0c;这个库被用于基于 C 的 Windows 应用程序的开发。当 Windows 或软件上显示“mfc140.dll丢失”或“找不到 mfc140.dll”这类错误信息时&#xff0c;表示你的系统可能缺少与 Visual C 相关的组件或这些组件…

软考:软件设计师 — 14.算法基础

十四. 算法基础 1. 算法的特性 算法是对特定问题求解步骤的描述&#xff0c;它是指令的有限序列&#xff0c;其中每一条指令表示一个或多个操作。 有穷性&#xff1a;执行有穷步之后结束&#xff0c;且每一步都可在有穷时间内完成。确定性&#xff1a;算法中每一条指令必须有…

代码随想录算法训练营第三十五天 | 416. 分割等和子集

416. 分割等和子集 题目链接&#xff1a;力扣题目链接 文章讲解&#xff1a;代码随想录 视频讲解&#xff1a;动态规划之背包问题&#xff0c;这个包能装满吗&#xff1f;| LeetCode&#xff1a;416.分割等和子集 给定一个只包含正整数的非空数组。是否可以将这个数组分割…

面向对象01:类和对象的创建

本节内容视频链接&#xff1a;面向对象04&#xff1a;类与对象的创建_哔哩哔哩_bilibilihttps://www.bilibili.com/video/BV12J41137hu?p63&vd_sourceb5775c3a4ea16a5306db9c7c1c1486b5 1.类、对象定义及关系 类&#xff08;‌Class&#xff09;‌是一个模板或蓝图&#…

如何规避DDoS攻击带来的风险?服务器DDoS防御软件科普

DDoS攻击是目前最常见的网络攻击方式之一。其见效快、成本低的特点&#xff0c;使它深受不法分子的“喜爱”。对于未受保护的企业来说&#xff0c;每次DDoS攻击的平均成本为20万美元&#xff0c;当DDoS攻击汹涌而至&#xff0c;缺失详细的保护预案&#xff0c;企业很可能会陷入…

erlang学习:gen_server书上案例22.6练习题4

昨天没有输出Fun中的io的原因是因为在任务函数中没有调用Fun方法&#xff0c;相当于只传了Fun函数但是没有进行调用&#xff0c;因此没有执行Fun函数&#xff0c;所以控制台中没有进行io的输出&#xff0c;今天在add_job中调用了Fun方法并执行&#xff0c;所以输出了相应的io。…

图像数据处理22

五、边缘检测 5.4 Hough变换 该技术主要用于检测图像中的基本形状&#xff0c;如直线、圆、椭圆等。 Hough变换的基本原理 Hough变换的基本原理是将图像空间中的直线或曲线变换到参数空间中&#xff0c;通过检测参数空间中的极值点&#xff08;局部最大值&#xff09;&…

自制镜像(贫穷版)

在装了docker的机子root目录操作 mkdir -p docker-images/tomcat-image/ cd docker-images/tomcat-image/ 把这两个红框的拉到docker-images/tomcat-image/ vim Dockerfile #导入基础镜像 from centos:7 #定义作者 maintainer GGBond<2958458916qq.com&…

SpringCloudGateway重写负载均衡策略

背景 gateway中多实例请求转发&#xff0c;默认采用轮训转发策略。在有些场景下&#xff0c;某些请求想固定到某一台实例上&#xff0c;这里通过重写默认负载均衡策略的方式实现。 以下代码为&#xff0c;大文件分片上传&#xff0c;多实例场景&#xff0c;根据文件md5和实例…

OpenCV c++ 实现图像马赛克效果

VS2022配置OpenCV环境 关于OpenCV在VS2022上配置的教程可以参考&#xff1a;VS2022 配置OpenCV开发环境详细教程 图像马赛克 图像马赛克&#xff08;Image Mosaic&#xff09;的原理基于将图像的特定区域替换为像素块&#xff0c;这些像素块可以是纯色或者平均色&#xff0c…

行业智能化的“火车头效应”,由星河AI金融网络启动

相信大多数人都认可&#xff0c;在行业智能化的列车中&#xff0c;金融是毋庸置疑的“火车头”。 有数据显示&#xff0c;目前AI整体渗透率只有4%&#xff0c;不同行业的AI渗透度有极大差异。其中&#xff0c;金融由于数字基础好&#xff0c;拥抱新技术的意愿强烈&#xff0c;成…

QT中通过Tcp协议的多线程的文件传输(服务器)

首先新建一个项目命名为SendClientSever 因为要进行网络通信&#xff0c;在pro文件的第一行代码中添加network 一、窗口设计 拖一个Widget里面放入label,lineEdit,pushbutton&#xff0c;名称如图修改 程序设计 子线程recvfile类 新建一个类用来执行子线程 将新建的类的头…

2-74 基于matlab的图像k-means聚类GUI

基于matlab的图像k-means聚类GUI&#xff0c;可对彩色图像进行Kmeans和meanshift进行聚类分析&#xff0c;生成最后的聚类图像以及聚类中心的迭代轨迹。程序已调通&#xff0c;可直接运行。 2-74 matlab GUI - 小红书 (xiaohongshu.com)

如何使用Python实现招聘数据的ftree算法可视化分析?大数据实战指导

&#x1f393; 作者&#xff1a;计算机毕设小月哥 | 软件开发专家 &#x1f5a5;️ 简介&#xff1a;8年计算机软件程序开发经验。精通Java、Python、微信小程序、安卓、大数据、PHP、.NET|C#、Golang等技术栈。 &#x1f6e0;️ 专业服务 &#x1f6e0;️ 需求定制化开发源码提…