I have N Servers, N DBs and N configuration. see the scenario below
So, on every request , I need to access server and db based on configuration.
How can implement dynamically data source in spring data jpa?
I have N Servers, N DBs and N configuration. see the scenario below
So, on every request , I need to access server and db based on configuration.
How can implement dynamically data source in spring data jpa?
You can try AbstractRoutingDatasource provided by Spring since version 2.0.1. using which you can dynamically use appropriate data-source . For integration with Spring data JPA check this very good example. In your case since your configurations are in DB instead of properties file you would need to perform an extra first database lookup to get the appropriate database configuration and return appropriate data-source object.
Another simple approach can be reloading different properties per environment;
Indeed, it might be overkill for DB switching, but it keeps your app simple and maintainable, and most importantly, keeps your environments completely isolated.
Step 1: Configure different properties file per each configuration you have (keep them in src/main/resources with the this naming convention: application-profile.properties)
Step 2: In runtime, change the application context to reload your app based on a given profile
Sample code:
In 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;
}
}
In 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();
}
© 2022 - 2024 — McMap. All rights reserved.