问题描述
我正在 Spring Data mongodb 中启动一个多租户项目.阅读完这篇帖子后,收藏每个租户在 mongodb 中是一个相当不错的方法.
I am starting a MULTI-TENANT project in spring data mongodb.After reading this post, collection per tenant is a pretty decent approach in mongodb.
那么我如何在 Spring Data Mongo 中实现这一点?显然,没有提供开箱即用的解决方案,但我认为我可以通过覆盖确定集合名称方法来调整 MongoTemplate,但我认为它不是公共或受保护的方法.
So how can I achieve this in Spring Data Mongo? Apparently, There's no out-of-box solution provided, but I thought I could tweak MongoTemplate by overriding determineCollectionName method but I assume its not a public nor protected method for purpose.
但是,我通过扩展 SimpleMongoDbFactory 并使用 LocalThread 变量,按照提供的提示轻松设置每个租户的数据库 此处.
However, I set up database per tenant approach very easily by extending SimpleMongoDbFactory and using LocalThread variable by following the tips provided here.
所以,问题是:
- 有什么安全的方法可以覆盖集合和域类名称映射?ps:这应该在运行时发生,所以我认为@collection 注释根本没有帮助.
- 如果每个租户的收集是不可能的,那么采用多数据库方法会带来多少性能和资源损失?
推荐答案
您可以扩展 MappingMongoEntityInformation 以覆盖 getCollectionName().存储库操作对每个操作调用 getCollectionName().我假设tenantId 将是一个ThreadLocal
You could extend MappingMongoEntityInformation to override getCollectionName(). The repository operations call getCollectionName() on each operation. I'm assuming the tenantId would be a ThreadLocal
public class TenantThreadLocal extends ThreadLocal<String> {
private final static TenantThreadLocal instance = new TenantThreadLocal();
public static TenantThreadLocal instance() {
return instance;
}
}
以及省略构造函数的重写类.
And the overridden class with the constructors omitted.
public class TenantMappingMongoEntityInformation<T, ID extends java.io.Serializable> extends MappingMongoEntityInformation<T, ID> {
@Override
public String getCollectionName() {
return TenantThreadLocal.instance().get() + super.getCollectionName();
}
}
然后创建您的存储库:
MongoPersistentEntity<YourObject> persistentEntity =
(MongoPersistentEntity<YourObject>)
mongoOperations.getConverter()
.getMappingContext()
.getPersistentEntity(YourObject.class);
MongoEntityInformation<YourObject, ObjectId> mongoEntityInformation =
new MappingMongoEntityInformation<YourObject, ObjectId>(persistentEntity);
CrudRepository<YourObject, ObjectId> repository =
new SimpleMongoRepository<YourObject, ObjectId>(mongoEntityInformation, mongoOperations);
这篇关于Spring Data mongo 中基于集合的多租户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!