-
-
Save rajgupta5989/0f628c53c9807cc039ea2cecd44f20a8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MultiTenantMongoDbFactory extends SimpleMongoClientDatabaseFactory { | |
public static final String DEFAULT_DB_INSTACE = "test"; | |
private final MultiTenantMongoConfig multiTenantMongoConfig; | |
public MultiTenantMongoDbFactory(final MultiTenantMongoConfig multiTenantMongoConfig, final MultiTenantMongoConfig.TenantMongoClient tenantMongoClient) { | |
super(tenantMongoClient.getMongoClient(), tenantMongoClient.getDatabase()); | |
this.multiTenantMongoConfig = multiTenantMongoConfig; | |
} | |
@Override | |
public MongoDatabase getMongoDatabase() throws DataAccessException { | |
final String tenant = TenantContext.getTenantId(); | |
MongoDatabase database = null; | |
if (tenant != null) { | |
final MultiTenantMongoConfig.TenantMongoClient tenantMongoClient = multiTenantMongoConfig.getMultiTenantConfig().get(tenant); | |
if (tenantMongoClient == null) { | |
throw new TenantNotFoundException("Tenant " + tenant + " is not configured"); | |
} | |
database = tenantMongoClient.getMongoClient().getDatabase(tenantMongoClient.getDatabase()); | |
} else { | |
database = getMongoClient().getDatabase(DEFAULT_DB_INSTACE); | |
} | |
return database; | |
} | |
@Override | |
public void destroy() throws Exception { | |
multiTenantMongoConfig.getMultiTenantConfig().values().forEach(mongo -> mongo.getMongoClient().close()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment