当 Spring 配置文件或自定义数据库属性文件中的数据库名称、密码或主机名等数据库属性发生更改时,我尝试更新 Spring Boot 中的数据源。当属性更改时,应用程序必须通过侦听属性更改来自行更新。
一旦数据库配置发生更改,我就使用 Spring 执行器来/重新启动 bean。但用户必须明确发出发布请求才能重新启动。必须通过监听更改并更新数据源来避免此步骤。
你能告诉我在 Spring boot 中做到这一点的最佳方法吗?
找到了一种动态更新数据源的方法,
我已向应用程序提供了包含数据库属性的外部 spring 配置文件,然后使用数据源 bean 的 @RefreshScope 刷新属性。
线程监视文件更改并调用执行器刷新()方法。
数据库.属性
dburl=jdbc://localhost:5432/dbname
dbusername=user1
dbpassword=userpwd
创建数据源,
@RefreshScope
public class DBPropRefresh {
@Value("${dburl}")
private String dbUrl;
@Value("${dbusername}")
private String dbUserName;
@Value("${dbpassword}")
private String dbPassword;
@Bean
@RefreshScope
public DataSource getDatasource() {
return new DatasourceBuilder().create().url(dbUrl).username(dbUserName).password(dbPassword);
}
}
向应用程序提供外部配置文件,
java -jar myapplication.jar --spring.config.location=database.properties
我创建了一个Java线程类来监视database.properties文件的更改。已关注https://dzone.com/articles/how-watch-file-system-changes https://dzone.com/articles/how-watch-file-system-changes当有变化时,它会调用refreshEndPoint.refresh()。
在 pom.xml 中,
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
<version>1.5.6.RELEASE</version>
</dependency>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)