Spring Boot - 如何管理同一微服务上的多个租户的配置

问题描述 投票:0回答:1

如何管理多个租户的 Spring Boot 应用程序中的配置?使用 spring 配置服务器可以实现这一点吗?

例如

spring-boot configuration microservices multi-tenant spring-cloud-config-server
1个回答
0
投票

根据我的理解,我们可以通过添加租户特定属性并从 git 存储库或其他自定义位置(可以通过类路径等标识)加载它们来使用配置服务器中的配置

请参阅该部分

动态租户识别 - 简单的方法 在 blogpost 中,我们从 URL 中识别租户,然后从文件中加载给定租户的必要配置。 这种方法更容易理解,但是在生产就绪的应用程序中,我们必须管理此读取过程以保证线程安全,并有效地完成清理。

我很久以前就做了一些探索,并记录了帖子中的要点,希望对你有帮助。

租户 1 的租户特定配置示例

# application-tenant1.properties
greeting.message=Hello from Tenant 1!

租户 2 的租户特定配置示例

# application-tenant2.properties
greeting.message=Hello from Tenant 2!

从配置中读取每个租户的设置

@RestController
public class MyAppController {
    
@Value("${greeting.message}")
private String greetingMessage;

@GetMapping("/greeting/{tenant}")
public String getGreetingMessage(@PathVariable String tenant) {
    // Set the active profile dynamically based on the tenant
    System.setProperty("spring.profiles.active", tenant);
    try {
        // Business logic using the tenant-specific profile
        return greetingMessage;
    } finally {
        // Clean up the active profile to avoid affecting subsequent requests
        System.clearProperty("spring.profiles.active");
    }
}
}

如果您希望在通过过滤器或其他方法找到租户标识作为每个请求的一部分后为每个租户加载动态配置,我们可以从数据库加载配置并设置类似于身份验证的租户上下文并将其用于每个请求,这将更加强大且易于扩展以进行动态租户管理。

© www.soinside.com 2019 - 2024. All rights reserved.