mysql与mangodb多租户,制作spring-data-mongodb多租户

In a post last august sbzoom proposed a solution to make spring-data-mongoDB multi-tenant:

"You have to make your own RepositoryFactoryBean. Here is the example from the Spring Data MongoDB Reference Docs. You would still have to implement your own MongoTemplate and delay or remove the ensureIndexes() call. But you would have to rewrite a few classes to make sure your MongoTemplate is called instead of Spring's."

Did anybody implement this or something equivalent?

解决方案

There's quite a few ways to skin the cat here. It essentially all boils down to on which level you'd like to apply the tenancy.

Basics

The basic approach is to bind some kind of key identifying the customer on a per-thread basis, so that you can find out about the customer the current thread of execution deals with. This is usually achieved by populating a ThreadLocal with some authentication related information as you can usually derive the tenant from the logged in user.

Now if that's in place there's a few options of where to apply the tenant knowledge. Let me briefly outline the most common ones:

Multi-tenancy on the database level

One way to separate data for multiple clients is to have individual databases per tenant. Spring Data MongoDB's core abstraction for this is the MongoDBFactory interface. The easiest way here is to override SimpleMongoDbFactory.getDb(String name) and call the parent method with the database name e.g. enriched by the tenant prefix or the like.

Multi-tenancy on the collection level

Another option is to have tenant specific collections, e.g. through tenant pre- or postfixes. This mechanism can actually be leveraged by using the Spring Expression language (SpEl) in the @Document annotation's collectionName attribute. First, expose the tenant prefix through a Spring bean:

@Component("tenantProvider")

public class TenantProvider {

public String getTenantId() {

// … implement ThreadLocal lookup here

}

}

Then use SpEL in your domain types @Document mapping:

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

public class Account { … }

SpEl allows you to refer to Spring beans by name and execute methods on them. MongoTemplate (and thus the repository abstraction transitively) will use the mapping metadata of the document class and the mapping subsystem will evaluate the collectionName attribute to find out about the collection to interact with.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值