spring启动时加载外部配置并实现在不重启应用的情况下修改druid连接池的配置
创始人
2025-05-30 12:02:49
0

平常同学们使用spring搭建工程时一些应用配置信息(例如数据库的连接配置、中间件的连接配置、第三方API等。。。)都是写在工程的classpath路径下的application-xxx.yml配置文件中,这样通常会存在一个问题,比如应用换库了或者数据库密码修改了,或者API信息变更了,遇到这些情况咱们的做法都是,先修改应用中的配置然后在重新打包并启动应用,所以很麻烦也容易出错,如果应用是分布式的还得在多折腾几遍。那么咱们能不能把这些配置集中写到一个地方呢,然后让spring启动时加载我们的外部配置,遇到配置变更只需要修改外部的配置文件然后重启应用就可以,省掉了重新打包的过程。

1、spring启动时加载外部配置解决方案

针对上述诉求我们可以使用springboot提供的spi机制spring Factories。它类似一种插件机制,第三方根据spingboot规定的方式配置自己的实现,然后springboot会在启动时扫描加载并初始化该配置,在spring-boot下有很多相关配置。

在这里插入图片描述

1.1、springgboot加载spring factories原理

springboot在初始化时会加载当前类路径以及jar包中META-INF/spring.factories文件。

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

如果普通bean想使用该机制必须要加@configuration注解,并且在spring.factories中标注为org.springframework.boot.autoconfigure.EnableAutoConfiguration。如下图中咱们测试的类TestBean被初始化了。

在这里插入图片描述

1.2、spring启动时加载外部配置文件(这里以加载外部数据库配置讲解)

上面讲解了下spring.factories的加载原理,那么我们就可以使用该机制在应用启动前加载外部数据库配置到spring容器中,然后在实例化datasource的时候从容器中获取该配置。具体的我们可以自定义一个类并实现Environment的后置处理接口EnvironmentPostProcessor并重写其postProcessEnvironment方法。

在这里插入图片描述

首先加载磁盘上的配置文件,当然该配置文件也可以从网络上获取(使用UrlResource),然后使用PropertiesPropertySourceLoader加载配置并添加到ConfigurableEnvironment中。

package com.bbs.config;import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.boot.env.PropertiesPropertySourceLoader;
import org.springframework.boot.env.PropertySourceLoader;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;import java.io.IOException;
import java.util.List;/*** @Author whh* @Date: 2023/03/17/ 23:13* @description** 使用spring上下文环境的后期处理接口加载外部的配置文件* 然后通过springboot的spi机制加载*/
public class DiskPropertyLoadProcessor implements EnvironmentPostProcessor {private final PropertySourceLoader propertyLoader = new PropertiesPropertySourceLoader();@Overridepublic void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {//        new UrlResource()Resource resource = new FileSystemResource("/BBS/bbs.properties");try {List> load = propertyLoader.load(resource.getFilename(), resource);for (PropertySource e : load) {environment.getPropertySources().addFirst(e);}} catch (IOException e) {e.printStackTrace();}}
}

新建咱们自己的spring.factories,在resource目录下新建META-INF文件夹然后新建spring.factories将咱们自己的配置写进去。

org.springframework.boot.env.EnvironmentPostProcessor=\
com.bbs.config.DiskPropertyLoadProcessor
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.bbs.util.TestBean  

从ConfigurableEnvironment 中获取配置初始化DruidDatasource。

 @Bean@Primarypublic DataSource ds(ConfigurableEnvironment env) throws SQLException {MutablePropertySources propertySources = env.getPropertySources();PropertySource propertySource = propertySources.get("bbs.properties");String userName = (String) propertySource.getProperty("db.username");String password = (String) propertySource.getProperty("db.password");DruidDataSource ds = new DruidDataSource();ds.setUrl("jdbc:mysql://localhost:3306/mydb?useUnicode=true&rewriteBatchedStatements=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true");ds.setDriverClassName("com.mysql.cj.jdbc.Driver");ds.setUsername(userName);ds.setPassword(password);ds.setInitialSize(3);ds.setMinIdle(3);ds.setMaxActive(5);ds.setTestWhileIdle(true);ds.setValidationQuery("select 1");ds.init();return ds;}

2、如何在不重启应用的情况下修改druid连接池的配置

上面我们实现了从外部文件加载配置,但是还是要重启应用才能让配置生效,那么咱们能不能在不重启应用的情况下让配置生效呢。实现上面的诉求可以分为如下两步:

  1. 监听磁盘上配置文件的变化
  2. 当文件变化时重新初始化连接池的配置

这里咱们自定义了一个DiskDBPropertyMonitor类并实现了ApplicationContextAware 接口,主要逻辑就是开启一个线程不断轮询文件所发生的事件,如果检测到文件修改事件那么就从spring的容器中获取当前的数据源,然后重新加载磁盘上的配置并更新数据源的配置。
由于DiskDBPropertyMonitor需要ApplicationContext所以需要将其配置到spring容器中。

package com.bbs.util.filemonitor;import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.io.FileSystemResource;import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.*;
import java.util.Properties;/*** @Author whh* @Date: 2023/03/18/ 13:26* @description*/
public class DiskDBPropertyMonitor implements ApplicationContextAware {//文件监听器private final WatchService watcher;//文件监听器返回的keyprivate final WatchKey watchKey;//监听的文件目录private final Path path;//文件的最后修改时间private long lastModify;private ApplicationContext ctx;/*** @param dir* @throws IOException*/public DiskDBPropertyMonitor(File dir) throws IOException {this.watcher = FileSystems.getDefault().newWatchService();//注册文件夹监听path = Paths.get(dir.getAbsolutePath());this.watchKey = path.register(watcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY);//new Thread(this::monitor,"Thread-DiskDBPropertyMonitor").start();}/*** 监控外部数据配置文件的情况并重新初始化数据源*/public void monitor() {for (; ; ) {try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}for (WatchEvent event : watchKey.pollEvents()) {WatchEvent.Kind kind = event.kind();if (kind == StandardWatchEventKinds.OVERFLOW) {continue;}WatchEvent ev = (WatchEvent) event;Path context = ev.context();Path child = this.path.resolve(context);File file = child.toFile();if (StandardWatchEventKinds.ENTRY_MODIFY.name().equals(kind.name()) && lastModify != file.lastModified() && file.length() > 0) {this.lastModify = file.lastModified();DruidDataSource druidDataSource = ctx.getBean(DruidDataSource.class);if (druidDataSource != null) {FileSystemResource resource = new FileSystemResource(file.getPath());try (InputStream is = resource.getInputStream()) {Properties props = new Properties();props.load(is);if (druidDataSource.isInited()) {druidDataSource.close();druidDataSource.restart();druidDataSource.setUsername((String) props.get("db.username"));druidDataSource.setPassword((String) props.get("db.password"));} else {druidDataSource.setUsername((String) props.get("db.username"));druidDataSource.setPassword((String) props.get("db.password"));}druidDataSource.init();} catch (Exception e) {e.printStackTrace();}}}}}}@Overridepublic void setApplicationContext(ApplicationContext applicationContext) throws BeansException {this.ctx = applicationContext;}public interface MonitorProcessor {void process(File file);}}
将DiskDBPropertyMonitor注册到spring容器中
    @Beanpublic DiskDBPropertyMonitor diskDBPropertyMonitor() throws IOException {DiskDBPropertyMonitor monitor = new DiskDBPropertyMonitor(new File("/BBS"));return monitor;}

3、写在后面

生产上数据库一般是被公共纳管的,所以我们也可以提供一个回调的API,当被纳管的数据库配置变更时纳管方或者其代理可以回调我们提供的API也能达到上述的目的。

相关内容

热门资讯

安卓系统怎么关钥匙,轻松掌握钥... 手机里的安卓系统,是不是有时候让你觉得有点儿头疼?比如,当你想关掉手机,却发现钥匙在哪里呢?别急,今...
安卓系统有隐私空间,打造安全私... 你知道吗?在智能手机的世界里,安卓系统可是个超级明星呢!它不仅功能强大,而且现在还悄悄地给你准备了一...
安卓系统设置角标,打造专属通知... 你有没有发现,手机上的安卓系统设置里有个神奇的小功能——角标?这个小东西虽然不起眼,但作用可大了去了...
安卓系统定位信息查询,揭秘移动... 你有没有想过,你的手机里藏着多少秘密?尤其是那个安卓系统,它可是个超级侦探,随时随地都在帮你定位。今...
安卓刷入系统恢复,轻松实现设备... 手机系统崩溃了?别慌!安卓刷入系统恢复大法来啦! 手机,这个我们生活中不可或缺的小伙伴,有时候也会闹...
安卓系统限制无法录音,探索无法... 你有没有遇到过这种情况?手机里明明装了录音软件,却突然发现,哎呀妈呀,竟然无法录音了!这可真是让人头...
怎么降级手机系统安卓,操作指南... 手机系统升级了,新功能层出不穷,但有时候,你可能会觉得,这系统太卡了,想回到那个流畅如丝的年代。别急...
米oa系统是安卓系统吗,深入解... 亲爱的读者,你是否曾好奇过,米OA系统是不是安卓系统的一员?这个问题,就像是一颗好奇的种子,悄悄地在...
手机刷安卓车载系统,手机刷机后... 你有没有发现,现在开车的时候,手机和车载系统之间的互动越来越紧密了呢?想象当你驾驶着爱车,一边享受着...
vivo安卓怎么降系统,viv... 手机用久了,是不是觉得系统越来越卡,运行速度大不如前?别急,今天就来教你怎么给vivo安卓手机降降级...
nova 4刷安卓系统,体验全... 最近手机界可是热闹非凡呢!听说华为nova 4要刷安卓系统了,这可真是让人兴奋不已。你有没有想过,你...
如果当初没有安卓系统,科技世界... 想象如果没有安卓系统,我们的生活会是怎样的呢?是不是觉得有点不可思议?别急,让我们一起穿越时空,探索...
安卓电视装win系统,系统转换... 亲爱的读者们,你是否曾想过,在你的安卓电视上装一个Windows系统,让它瞬间变身成为一台功能强大的...
安卓手机还原系统好处,重拾流畅... 你有没有遇到过安卓手机卡顿、运行缓慢的情况?别急,今天就来给你揭秘一下安卓手机还原系统的那些好处,让...
安卓系统能跑win吗,探索跨平... 你有没有想过,你的安卓手机里能不能装上Windows系统呢?这听起来是不是有点像科幻电影里的情节?别...
安卓车载系统蓝牙设置,畅享智能... 你有没有发现,现在开车的时候,手机和车载系统之间的互动越来越频繁了呢?这不,今天就来给你详细说说安卓...
奥利奥安卓系统,探索新一代智能... 你有没有想过,一块小小的奥利奥饼干竟然能和强大的安卓系统扯上关系?没错,今天就要来聊聊这个跨界组合,...
微信使用安卓系统,功能解析与操... 你有没有发现,现在用微信的人越来越多了呢?尤其是安卓系统的用户,简直就像潮水一样涌来。今天,就让我带...
体验最新原生安卓系统,极致体验... 你有没有想过,手机系统就像是我们生活的调味品,有时候换一种口味,生活都会变得有趣起来呢?最近,我体验...
安卓系统能玩原神,尽享奇幻冒险... 你有没有想过,在安卓系统上也能畅玩《原神》这样的热门游戏呢?没错,就是那个画面精美、角色丰富、玩法多...