MongoDB实现Multi tenant的方法

this is an example on how to implement the multi tenancy by using MongoDB. Tenant separation is done by schema separation.

Tenant resolver to get the tenant for current request

@Component
 public class TenantResolver {
     public static final String HEADER_HYBRIS_TENANT = "hybris-tenant";
 
     private String defaultTenant;
 
     public String getCurrentTenant() {
         return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader(HEADER_HYBRIS_TENANT);
 
     }
 
 }
  1. Document annotation to specify the collection name
@Document(collection = "#{tenantResolver.getCurrentTenant()}_config")
public class Config {
...
}

Test:

Created different collections according to the tenant:

db.getCollectionNames()

[ “config”, “t1_config”, “t2_config”, “t3_config”, “users” ]

Data from different tenant is stored into the corresponding collection:

db.t1_config.find()

{ “_id” : “test1”, “_class” : “com.example.model.Config”, “value” : “value” }

db.t2_config.find()

{ “_id” : “test2”, “_class” : “com.example.model.Config”, “value” : “value” }

db.t3_config.find()

{ “_id” : “test3”, “_class” : “com.example.model.Config”, “value” : “value” }

展开阅读全文
©️2020 CSDN 皮肤主题: 深蓝海洋 设计师: CSDN官方博客 返回首页
实付0元
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值