我需要修改Spring-Boot应用程序以动态管理Mongo驱动程序实例。在我的应用程序中,已经配置了Spring Boot MongoDB存储库,现在可以访问了。对于新要求,我们要实现sass(动态承租人),其中一个是主数据库,另一个是动态选择数据库。现在的问题是,当我们选择任何租户时,如何在应用程序中动态配置spring引导另一个MongoDB存储库。 例如:假设5个租户在应用程序内部动态选择其中任何一个,而另一个数据库则是随机选择的
答案 0 :(得分: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;
}