我正在开发一个多租户REST spring boot应用程序。我能够根据每个请求中的标头值在不同的数据源之间动态切换。但我的问题是在application.properties文件上。不同的租户在其属性文件中的相同属性具有不同的值。
如何将每个租户的属性文件分开,并根据请求头中的值动态确定要使用的属性文件
发布于 2019-09-30 18:01:18
你不能在运行时切换配置文件。您的选择仅限于创建一个有其自身缺点的新ApplicationContext,或者您可以在启动时加载租户属性文件,并实现特定于租户的getProperty方法,以便在需要时调用。
这应该-处理后一种情况:
@Component
public class TenantProperties {
private Map<String, ConfigurableEnvironment> customEnvs;
@Inject
public TenantProperties(@Autowired ConfigurableEnvironment defaultEnv,
@Value("${my.tenant.names}") List<String> tenantNames) {
this.customEnvs = tenantNames
.stream()
.collect(Collectors.toMap(
Function.identity(),
tenantId -> {
ConfigurableEnvironment customEnv = new StandardEnvironment();
customEnv.merge(defaultEnv);
Resource resource = new ClassPathResource(tenantId + ".properties");
try {
Properties props = PropertiesLoaderUtils.loadProperties(resource);
customEnv.getPropertySources()
.addLast(new PropertiesPropertySource(tenantId, props));
return customEnv;
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}));
}
public String getProperty(String tenantId, String propertyName) {
ConfigurableEnvironment ce = this.customEnvs.get(tenantId);
if (ce == null) {
throw new IllegalArgumentException("Invalid tenant");
}
return ce.getProperty(propertyName);
}
}您需要向包含以逗号分隔的租户名称(name1, name2等)列表的主应用程序属性添加my.tenant.names属性。租户特定的属性是从name1.properties加载的,...从类路径。你明白了吧。
发布于 2019-09-28 23:18:31
Spring配置文件在您的情况下可以工作。
如果租户是静态的,仅在启动服务之前预测租户及其属性,那么我建议tovgo使用静态配置文件。
如果某些属性可以在服务为其他租户提供服务时进行更改,那么最好使用config server,这样无需重启即可更改这些属性。
如果租户是动态的,你可以根据你的数据点选择db,如果租户数量可能大幅增加。
https://stackoverflow.com/questions/58147432
复制相似问题