弹簧配置/属性因请求而异

时间:2019-04-10 14:49:27

标签: spring

我需要弄清楚在Spring中是否可能出现以下情况。

如果每个区域有不同的服务/数据库,Spring是否可以根据单个部署中的请求促进对这些服务/数据库的调用?举个例子,来自用户X的所有请求将定向到EAST区域中的服务/数据库,而来自用户Y的所有请求将定向到WEST区域中的服务/数据库。

显然,到每个数据库的连接将使用连接池,因此配置将需要不同,而不仅仅是属性。初始化其他服务时,将完成身份验证,因此不仅仅与数据库连接有关。

这是Spring,我想避免不得不传递实现。我可以指示Spring对每个请求使用特定的配置吗?有没有更好的方法可以做到这一点?

-编辑-

从技术上讲,可以做到这一点,尽管这并不容易维护。

@Configuration
@PropertySource("classpath:region1.properties")
public class TestIndependentConfigurationRegion1Configuration {

    @Bean
    public String sampleServiceUrl(@Value("${sample.service.url}") String value) {
        return value;
    }

    @Bean
    public TestIndependentConfigurationSampleService testSampleService() {
        return new TestIndependentConfigurationSampleService();
    }

}
@Configuration
@PropertySource("classpath:region2.properties")
public class TestIndependentConfigurationRegion2Configuration {

    @Bean
    public String sampleServiceUrl(@Value("${sample.service.url}") String value) {
        return value;
    }

    @Bean
    public TestIndependentConfigurationSampleService testSampleService() {
        return new TestIndependentConfigurationSampleService();
    }

}
@Controller
public class TestIndependentConfigurationController {

    protected ApplicationContext testRegion1ApplicationContext = new AnnotationConfigApplicationContext(TestIndependentConfigurationRegion1Configuration.class);

    protected ApplicationContext testRegion2ApplicationContext = new AnnotationConfigApplicationContext(TestIndependentConfigurationRegion2Configuration.class);

    @RequestMapping("/sample/service")
    @ResponseBody
    public String testSampleService() {
        TestIndependentConfigurationSampleService testSampleService = null;
        if(/* region 1 */) {
            testSampleService = (TestIndependentConfigurationSampleService) testRegion1ApplicationContext.getBean("testSampleService");
        }
        if(/* region 2 */) {
            testSampleService = (TestIndependentConfigurationSampleService) testRegion2ApplicationContext.getBean("testSampleService");
        }
        testSampleService.executeSampleService();
        return "SUCCESS";
    }

}

1 个答案:

答案 0 :(得分:0)

我认为您无法使用属性来做到这一点。但是,您应该查看与spring集成的(netflix)功能区客户端。功能区的某些功能使您可以在区域之间负载均衡请求。您可以自定义功能区客户端以执行所需的操作。

这里有些读物: https://cloud.spring.io/spring-cloud-netflix/multi/multi_spring-cloud-ribbon.html