【问题标题】:implement dynamically datasource in spring data jpa在spring data jpa中实现动态数据源
【发布时间】:2018-07-27 07:14:11
【问题描述】:

我有 N 个服务器、N 个 DB 和 N 个配置。看下面的场景

所以,对于每个请求,我都需要根据配置访问服务器和数据库。

spring data jpa中如何实现动态数据源?

【问题讨论】:

标签: spring spring-boot datasource dynamic-binding


【解决方案1】:

你可以试试 Spring 2.0.1 以后提供的AbstractRoutingDatasource。使用它,您可以动态使用适当的 data-source 。对于与 Spring 数据 JPA 的集成,请查看 this 非常好的示例。在您的情况下,由于您的配置位于数据库而不是属性文件中,因此您需要执行额外的第一个数据库查找以获取适当的数据库配置并返回适当的数据源对象。

【讨论】:

    【解决方案2】:

    另一种简单的方法是为每个环境重新加载不同的属性;

    确实,对于 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();
    }
    

    【讨论】:

      猜你喜欢
      • 2019-12-02
      • 1970-01-01
      • 2016-08-23
      • 2018-07-22
      • 1970-01-01
      • 2017-06-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多