简体   繁体   中英

Custom implementation of MongoDB Java Driver

I need to write an own implementation of "com.mongodb.MongoClient" in order to add the DB Credentials on the fly in MongoTemplate.

This is is because:
- we are working on a multitenant application and the databases are created on the fly.
- while autowiring the MongoTemplate (on server start-up), the credentials list passed to MongoClient would be changing.
- each time, when a new tenant is added, we could not re-inject the existing MongoTemplate.
- also, we have to use shared connection pool across all the tenants, therefore, we can not use different MongoTemplate for each tenant.

Can I write down my custom implementation of MongoClient? If yes, how it should be implemented to cater DB credentials change on the fly?

Note that, the "credentialsList" passed to "com.mongodb.MongoClient" construtor, is converted to "unmodifiableList", so that, it could not be updated.

Thanks!!

You can write your own MongoClient by extending the class but does it really required ? Not necessarily.

  1. MongoClientOptions provides the list of properties that you can configure

  2. Make use of following constructor of MongoClient

    public MongoClient(List serveraddress, List credentialsList, MongoClientOptions options) { super(seeds, credentialsList, options); }

to pass list of credentials, list of server address and their options.

  1. Create a SimpleMongoDBFactory using the MongoClient

  2. Finally make use of MongoDbFactory to create a MongoTemplate

To put all together:

    @Bean(destroyMethod="close")
    MongoClient mongoClient(MongoClientOptions mongoClientOptions){

        MongoClient mongoClient=new MongoClient(serverAddresses(),credentails(),mongoClientOptions);

        return mongoClient;
    }


    @Bean
    public  MongoClientOptions mongoClientOptions(){

        MongoClientOptions.Builder builder = MongoClientOptions.builder();
        MongoClientOptions options=builder.sslEnabled(true).build();        
        return options;
    }

    @Bean
    public MongoDbFactory mongoDbFactory(MongoClientOptions mongoClientOptions) throws Exception {
        return new SimpleMongoDbFactory(mongoClient(mongoClientOptions), "yourdb");
    }

    @Bean
    public MongoTemplate mongoTemplate(MongoClientOptions mongoClientOptions) throws Exception {

        MongoTemplate mongoTemplate = new MongoTemplate(mongoDbFactory(mongoClientOptions));

        return mongoTemplate;

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM