Spring-data-mongodb connect to multiple databases in one Mongo instance

后端 未结 6 2155
死守一世寂寞
死守一世寂寞 2020-12-07 23:12

I am using the latest spring-data-mongodb (1.1.0.M2) and the latest Mongo Driver (2.9.0-RC1). I have a situation where I have multiple clients connecting to my application a

6条回答
  •  情书的邮戳
    2020-12-07 23:39

    You may want to sub-class SimpleMongoDbFactory and strategize how the default DB as returned by getDb is returned. One option is to use thread-local variables to decide on the Db to use, instead of using multiple MongoTemplates.

    Something like this:

    public class ThreadLocalDbNameMongoDbFactory extends SimpleMongoDbFactory {
        private static final ThreadLocal dbName = new ThreadLocal();
        private final String defaultName; // init in c'tor before calling super
    
        // omitted constructor for clarity
    
        public static void setDefaultNameForCurrentThread(String tlName) {
            dbName.set(tlName);
        }
        public static void clearDefaultNameForCurrentThread() {
            dbName.remove();
        }
    
        public DB getDb() {
            String tlName = dbName.get();
            return super.getDb(tlName != null ? tlName : defaultName);
        }
    }
    

    Then, override mongoDBFactory() in your @Configuration class that extends from AbstractMongoConfiguration like so:

    @Bean
    @Override
    public MongoDbFactory mongoDbFactory() throws Exception {
      if (getUserCredentials() == null) {
          return new ThreadLocalDbNameMongoDbFactory(mongo(), getDatabaseName());
      } else {
          return new ThreadLocalDbNameMongoDbFactory(mongo(), getDatabaseName(), getUserCredentials());
      }
    }
    

    In your client code (maybe a ServletFilter or some such) you will need to call: ThreadLocalDBNameMongoRepository.setDefaultNameForCurrentThread() before doing any Mongo work and subsequently reset it with: ThreadLocalDBNameMongoRepository.clearDefaultNameForCurrentThread() after you are done.

提交回复
热议问题