MongoDB实现Multi tenant的方法

172 阅读1分钟

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” }