spring启动动态重置数据源

nwnhqdif  于 2021-07-03  发布在  Java
关注(0)|答案(3)|浏览(334)

当spring配置文件或自定义db属性文件中的db name、password或hostname等db属性发生更改时,我尝试在spring引导中更新datasource。当属性更改时,应用程序必须通过侦听对属性的更改自行更新。
我使用springactuator在db配置更改后重新启动bean。但用户必须显式地发出post请求才能重新启动。必须通过侦听更改和更新数据源来避免此步骤。
你能告诉我在 Spring 做这件事的最佳方法吗?

xzlaal3s

xzlaal3s1#

在我的项目中,我使用了多重租户。基本上,我在如下属性中定义了几个数据源:

primary.datasource.url=jdbc:postgresql://localhost:5432/db_name?currentSchema=schema_name
primary.datasource.username=user
primary.datasource.password=password
primary.datasource.driverClassName=org.postgresql.Driver
primary.datasource.driver-class-name=org.postgresql.Driver

secondary.datasource.url=jdbc:postgresql://localhost:5432/other_db?currentSchema=schema
secondary.datasource.username=user
secondary.datasource.password=password
secondary.datasource.driverClassName=org.postgresql.Driver
secondary.datasource.driver-class-name=org.postgresql.Driver

default.datasource.url=jdbc:postgresql://localhost:5432/default_db?currentSchema=public
default.datasource.username=user
default.datasource.password=password
default.datasource.driverClassName=org.postgresql.Driver
default.datasource.driver-class-name=org.postgresql.Driver

然后在配置类中定义多个数据源:

@Bean
@Primary
@ConfigurationProperties(prefix="primary.datasource")
public DataSource primaryDataSource() {
    return DataSourceBuilder.create().build();
}

@Bean
@ConfigurationProperties(prefix="secondary.datasource")
public DataSource secondaryDataSource() {
    return DataSourceBuilder.create().build();
}

@Bean
@ConfigurationProperties(prefix="default.datasource")
public DataSource defaultDataSource(){
    return DataSourceBuilder.create().build();
}

并在此基础上配置了多租户。
赞成的意见:
简单的租户切换,可以手动触发,甚至配置为在请求(筛选器)中的某些特定头上触发。
可以配置为在架构或数据库之间切换。
动态发生(您不必重新启动bean)
欺骗:
您必须在属性文件中定义所有db可能性。
你必须关闭模式验证,因为它会发疯。

lbsnaicq

lbsnaicq2#

您可以使用spring的动态数据源路由并检查它是否有用?这是一个非常古老的技术,如果这符合你的目的,它可能会派上用场。
但请注意-这是数据源路由,而不是新的数据源配置。
https://spring.io/blog/2007/01/23/dynamic-datasource-routing/

e0bqpujr

e0bqpujr3#

找到了一种动态更新数据源的方法,
我已经将包含db属性的外部spring配置文件提供给了应用程序,然后使用@refreshscope刷新了datasourcebean的属性。
线程监视文件更改并调用exactor refresh()方法。
数据库.properties

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 当有更改时,它会调用refreshendpoint.refresh()。
在pom.xml中,

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-actuator</artifactId>
  <version>1.5.6.RELEASE</version>
</dependency>

相关问题