gpt4 book ai didi

mongodb - Spring Data MongoDB 基于集合的 Multi-Tenancy

转载 作者:可可西里 更新时间:2023-11-01 09:10:36 29 4
gpt4 key购买 nike

我们的 Spring Boot 1.3.3 应用程序使用 Spring Data MongoDB 1.8.4 将数据保存在 MongoDB(2.6 或 3.2)上。

我们需要支持 Multi-Tenancy 。我们选择使用“基于集合”的 Multi-Tenancy ,即每个租户都有自己的集合。例如,对于 Article 实体,集合是“{tenantName}_articles”。

Oliver Gierke 在 Making spring-data-mongodb multi-tenant 中亲切地解释了一个实现使用例如:

@Document(collectionName = "#{tenantProvider.getTenantId()}_articles")

这在纸面上非常好,但似乎不适用于现实生活中的应用程序,因为我发现了两个问题,一个是主要问题:

问题 1(我可以接受):在应用程序启动时,Spring Boot 使数据库为具有自定义索引(例如 @Indexed 属性)的实体构建索引。但是在启动时,没有“当前租户”,因此 Spring Data 创建了不相关的集合,例如“_articles”。我们如何防止这种情况发生?

问题 2(这里是主要问题):在运行时,创建和使用 Multi-Tenancy 集合(例如“{tenantName}_articles”)没有自定义索引(除了“_id”上的默认 MongoDB 索引)。我怀疑 Spring 在运行时忽略了索引,因为它认为它已经在启动时完成了这项工作。这是一个主要的性能问题。我们该如何解决这个问题?

感谢您的宝贵时间。

最佳答案

找到了为给定租户重新创建索引的方法:

String tenantName = ...;

MongoMappingContext mappingContext = (MongoMappingContext) mongoTemplate.getConverter().getMappingContext();
MongoPersistentEntityIndexResolver resolver = new MongoPersistentEntityIndexResolver(mappingContext);

for (BasicMongoPersistentEntity entity : mappingContext.getPersistentEntities()) {
if (entity.findAnnotation(Document.class) == null) {
// Keep only collection roots
continue;
}

String collectionName = entity.getCollection();
if (!collectionName.startsWith(tenantName)) {
// Keep only dynamic entities
continue;
}

IndexOperations indexOperations = mongoTemplate.indexOps(collectionName);
for (MongoPersistentEntityIndexResolver.IndexDefinitionHolder holder : resolver.resolveIndexForEntity(entity)) {
indexOperations.ensureIndex(holder.getIndexDefinition());
}
}

我花了一些时间来弄清楚这一点。希望这会有所帮助。欢迎改进。

关于mongodb - Spring Data MongoDB 基于集合的 Multi-Tenancy ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37459810/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com