spring启动时加载缓存中数据

本文探讨了如何通过继承PropertyPlaceholderConfigurer类并重写mergeProperties()方法,将应用配置从文件加载到缓存中,进而实现Spring从缓存中读取JDBC等相关配置的优化策略。

        最近想把应用中的配置全部放到缓存中,以实现spring从缓存中读取jdbc等相关配置,通过对spring配置文件加载方法的了解,目前找到方法如下:

        1.继承配置文件类:org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;

        2.重写方法:mergeProperties();

        3.将新增的org.springframework.beans.factory.config.PropertyPlaceholderConfigurer子类配置到配置文件中;

        代码分析:

        抽象类PropertiesLoaderSupport中mergeProperties()方法会加载所有配置文件,代码如下:

/**
	 * Return a merged Properties instance containing both the
	 * loaded properties and properties set on this FactoryBean.
	 */
	protected Properties mergeProperties() throws IOException {
		Properties result = new Properties();

		if (this.localOverride) {
			// Load properties from file upfront, to let local properties override.
			loadProperties(result);
		}

		if (this.localProperties != null) {
			for (Properties localProp : this.localProperties) {
				CollectionUtils.mergePropertiesIntoMap(localProp, result);
			}
		}

		if (!this.localOverride) {
			// Load properties from file afterwards, to let those properties override.
			loadProperties(result);
		}

		return result;
	}
        从以上代码可以看到此方法的功能是将所有配置读取到Properties中,然后会在初始化bean、bean内部来使用这些属性,重写此方法后,此方法应有如下功能:

        a)加载配置文件中所有属性;

        b)加载用户所需的其他属性;

        代码如下:

        

        protected Properties mergeProperties() throws IOException {
                Properties allProperties = super.mergeProperties();
//              add other properties
                return allProperties;
        }
       暂时只找到此方法来加载缓存中的配置,没发现其他方式来实现此功能。

### 加载数据缓存的最佳实践 在Spring应用程序中,为了提高性能并减少数据库查询次数,通常会在应用启动时将常用的数据加载到内存中的缓存。以下是实现这一目标的一些最佳实践: #### 使用`CommandLineRunner`或`ApplicationListener` 可以通过实现 `CommandLineRunner` 接口或者监听 `ApplicationReadyEvent` 来执行初始化逻辑。这两种方式都可以确保在Spring容器完全初始化之后运行自定义代码。 ```java import org.springframework.boot.CommandLineRunner; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Component; @Component public class CacheLoader implements CommandLineRunner { private final MyService myService; public CacheLoader(MyService myService) { this.myService = myService; } @Override public void run(String... args) throws Exception { // 调用服务方法来填充缓存 myService.loadCache(); } } ``` 上述代码通过调用 `myService.loadCache()` 方法,在应用启动时触发缓存预热操作[^1]。 #### 配置缓存管理器 Spring Boot 提供了自动配置的缓存支持,默认情况下可以使用基于ConcurrentHashMap的简单缓存。如果需要更高级的功能(如过期时间、持久化),可以选择集成其他缓存提供者(例如 Ehcache 或 Redis)。可以在 `application.properties` 中指定缓存类型: ```properties spring.cache.type=redis ``` 对于Redis缓存的支持,需引入相应的依赖项,并确保服务器已正确安装和配置[^3]。 #### 缓存注解的应用 利用Spring框架内置的缓存注解简化开发流程。例如,标记某个方法的结果会被存储至特定名称的空间下以便后续重复访问无需重新计算。 ```java @Service public class MyService { @Cacheable(value = "items", key = "#id") public Item findById(Long id){ return repository.findById(id).orElse(null); } public void loadCache(){ List<Item> items = repository.findAll(); items.forEach(item -> findById(item.getId())); } } ``` 这里展示了如何结合 `@Cacheable` 注解与业务逻辑完成批量加载的任务[^2]。 #### 性能考量与其他建议 - **异步加载**:考虑采用多线程技术进行后台处理以免阻塞主线程。 - **监控健康状态**:定期检查缓存命中率以及大小调整策略是否合理有效。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值