我需要修改我的 Spring-Boot 应用程序以动态管理 Mongo 驱动程序的动态实例。在我的应用程序中,Spring Boot MongoDB Repositories 已经配置好了,现在可以了。对于新要求,我们要实现 sass(动态租户),其中一个是主数据库,另一个是动态选择数据库。现在的问题是,当我们选择任何租户时,如何在应用程序中动态配置 spring Boot another MongoDB Repositories。例如:假设 5 个租户在应用程序内动态选择其中任何一个,另一个 DB 随机选择
问问题
451 次
1 回答
0
DyanamicRepository dyanmicRepositry=CustomMongoDbMongoRepositoryFactoryClass.getRepository(Pass_DyanamicRepository.class, Pass_DynamicDataBaseName);
dyanmicRepositry.save(dealer);
******************************************
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.convert.CustomConversions;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
import org.springframework.data.mongodb.repository.support.MongoRepositoryFactory;
import com.mongodb.Mongo;
public final class CustomMongoDbMongoRepositoryFactoryClass {
static final Map<String,Object> LOCK_OBJECT=new HashMap<>();
private static final Map<String,MongoOperations> MONGOOP_CACHE=new HashMap<>();
private static final Map<String,Map<String,Object>> REPOS_CACHE=new HashMap<>();
public static MongoOperations getMongoOperations(Vendor vendor){
String database =vendor.getVendorName().replaceAll("[\\s]", "");
MongoOperations mongoOperations=MONGOOP_CACHE.get(database);
if(mongoOperations==null){
Mongo mongo=ApplicationContextHolder.getContext().getBean(Mongo.class);
CustomConversions mappingMongoConverter=ApplicationContextHolder.getContext().getBean(CustomConversions.class);
MongoTemplate mm = new MongoTemplate(mongo, database);
MappingMongoConverter mmc = (MappingMongoConverter)mm.getConverter();
mmc.setCustomConversions(mappingMongoConverter);
mmc.afterPropertiesSet();
mongoOperations= mm;
MONGOOP_CACHE.put(database,mongoOperations);
}
return mongoOperations;
}
public static synchronized <T extends Serializable> T getRepository(Class<T> type,Vendor vendor){
if(vendor.getId()=="") {
return ApplicationContextHolder.getContext().getBean(type);
}
String database =vendor.getVendorName().replaceAll("[\\s]", "");
Map<String,Object> repos=REPOS_CACHE.get(database);
if(repos==null) {
repos=new HashMap<>();
REPOS_CACHE.put(database,repos);
}
if(repos.containsKey(type.getName())) {
System.out.println("Get "+type.getName()+" Repo in ::: "+(System.currentTimeMillis()-start) +"ms");
return (T) repos.get(type.getName());
}
MongoOperations mongoOperations=getMongoOperations(vendor);
MongoRepositoryFactory bean=new MongoRepositoryFactory(mongoOperations);
T repo=bean.getRepository(type);
repos.put(type.getName(), repo);
return repo;
}
于 2018-10-31T05:07:31.217 回答