【发布时间】:2018-07-27 07:14:11
【问题描述】:
【问题讨论】:
-
这能回答你的问题吗? dynamically change Spring data source
标签: spring spring-boot datasource dynamic-binding
【问题讨论】:
标签: spring spring-boot datasource dynamic-binding
你可以试试 Spring 2.0.1 以后提供的AbstractRoutingDatasource。使用它,您可以动态使用适当的 data-source 。对于与 Spring 数据 JPA 的集成,请查看 this 非常好的示例。在您的情况下,由于您的配置位于数据库而不是属性文件中,因此您需要执行额外的第一个数据库查找以获取适当的数据库配置并返回适当的数据源对象。
【讨论】:
另一种简单的方法是为每个环境重新加载不同的属性;
确实,对于 DB 切换来说,这可能有点过头了,但它使您的应用程序保持简单和可维护,最重要的是,使您的环境保持完全隔离。
第 1 步:为每个配置配置不同的属性文件(使用以下命名约定将它们保存在 src/main/resources 中:application-profile.properties)
第 2 步:在运行时,更改应用程序上下文以根据给定配置文件重新加载您的应用程序
示例代码:
在 ProfileController 中:
@RestController
@RequestMapping("/profile")
public class ProfileController {
@Value("${spring.profiles.active}")
private String profile;
@GetMapping("/profile")
public String getProfile() {
System.out.println("Current profile is: " + profile);
return "Current profile is: " + profile;
}
@GetMapping("/switch/{profile}")
public String switchProfile(@PathVariable String profile) {
System.out.println("Switching profile to: " + profile);
**MyApplication.restartWithNewProfile(profile);**
return "Switched to profile: " + profile;
}
}
在 MyApplication.java 中:
/**
* Switching profile in runtime
*/
public static void restartWithNewProfile(String profile) {
Thread thread = new Thread(() -> {
context.close();
context = SpringApplication.run(MyApplication.class, "--spring.profiles.active=" + profile);
});
thread.setDaemon(false);
thread.start();
}
【讨论】: