我有一種情況,我有多個客戶端連接到我的應用程序,我想在同一個Mongo服務器中爲每個客戶端提供他們自己的「模式/數據庫」。如何使用Mongodb在spring-boot中使用多個dbs的單實例
我的配置類:
@Configuration
public class MongoDbConfiguration {
@Bean
@Primary
public MongoDbFactory mongoDbFactory() throws UnknownHostException {
return new MultiTenantMongoDbFactory();
}
@Bean
@Primary
public MongoTemplate mongoTemplate() throws UnknownHostException {
return new MongoTemplate(mongoDbFactory());
}
}
多租戶Db的工廠
public class MultiTenantMongoDbFactory extends SimpleMongoDbFactory {
public MultiTenantMongoDbFactory() throws UnknownHostException {
super(getMongoClient(), TenantContext.getTenant());
}
@Override
public DB getDb() throws DataAccessException {
String tenant = TenantContext.getTenant();
return getDb(tenant);
}
private static MongoClient getMongoClient() {
String tenant = TenantContext.getTenant();
System.out.println("Database name in factory class :"+tenant);
if (tenant.equalsIgnoreCase("ncet")) {
MongoCredential mongoCredential = MongoCredential.createCredential("user1", "db1",
"pwd1".toCharArray());
ServerAddress serverAddress = new ServerAddress("localhost", 27017);
MongoClient mongoClient = new MongoClient(serverAddress, Arrays.asList(mongoCredential));
return mongoClient;
}else{
MongoCredential mongoCredential = MongoCredential.createCredential("user1", "db2",
"pwd2".toCharArray());
ServerAddress serverAddress = new ServerAddress("localhost", 27017);
MongoClient mongoClient = new MongoClient(serverAddress, Arrays.asList(mongoCredential));
return mongoClient;
}
}
每個數據庫都有憑據
您的問題尚不清楚。這是身份驗證問題還是mongodb與多個dbs問題?你想配置一個副本集嗎?如果你有錯誤,你能否提供堆棧跟蹤? –
我在我的應用程序中使用了spring-data mongo存儲庫和彈簧引導。對於需要配置多個數據庫的單個mongo實例。應用程序有多個客戶端,每個客戶端都有專用數據庫試圖做多tency –
什麼是你得到的異常,在你的問題中發佈堆棧跟蹤 –