vis*_*mar 7 java spring spring-mvc spring-boot spring-boot-actuator
我正在尝试更新Spring Boot中的数据源,当数据库名称,密码或主机名等数据库属性在spring配置文件或自定义数据库属性文件中更改时.当属性更改时,应用程序必须通过侦听属性更改来自行更新.
一旦数据库配置发生变化,我就会使用Spring执行器来重启bean.但是用户必须明确地发布重新启动的请求.必须通过监听更改并更新数据源来避免此步骤.
你能告诉我在Spring启动时做到这一点的最佳方法吗?
找到了一种动态更新数据源的方法,
我已经给应用程序提供了包含数据库属性的外部spring配置文件,然后使用@RefreshScope为数据源bean刷新了属性。
线程监视文件更改,并调用执行器refresh()方法。
database.properties
dburl=jdbc://localhost:5432/dbname
dbusername=user1
dbpassword=userpwd
Run Code Online (Sandbox Code Playgroud)
创建数据源,
@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);
}
}
Run Code Online (Sandbox Code Playgroud)
将外部配置文件提供给应用程序,
java -jar myapplication.jar --spring.config.location=database.properties
我创建了一个Java线程类来监视database.properties文件的更改。跟随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>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6897 次 |
| 最近记录: |