如何在spring mvc中连接2个mongodb数据库

oxf4rvwz  于 2022-11-24  发布在  Spring
关注(0)|答案(1)|浏览(150)

嗨,我有这个配置文件来连接到我的远程mongodb服务,现在我需要同时连接1个数据库,但我不知道有人能帮我什么忙?

@Configuration
public class MongoConfig{
  
    @Bean
    public MongoDbFactory mongoDbFactory(){
        MongoClientURI uri = new MongoClientURI("mongodb://user:pass@localhost:27017/?authSource=admin");
  

        return new SimpleMongoDbFactory(new MongoClient(uri), "DataBuild");
       
    }
  
    @Bean
    public MongoOperations mongoOperations(){
        return new MongoTemplate(mongoDbFactory());
       
    }
    
    @Bean
    MongoTransactionManager transactionManager(MongoDbFactory dbFactory) {
      return new MongoTransactionManager(dbFactory);
    }
}
k2fxgqgv

k2fxgqgv1#

看一下this tutorial,下面是它们使用的@Configuration类:

@Configuration
public class MultipleMongoConfig {
    @Primary
    @Bean(name = "newdb1Properties")
    @ConfigurationProperties(prefix = "spring.data.mongodb.newdb1")
    public MongoProperties getNewDb1Props() throws Exception {
        return new MongoProperties();
    }

    @Bean(name = "newdb2Properties")
    @ConfigurationProperties(prefix = "spring.data.mongodb.newdb2")
    public MongoProperties getNewDb2Props() throws Exception {
        return new MongoProperties();
    }

    @Primary
    @Bean(name = "newdb1MongoTemplate")
    public MongoTemplate newdb1MongoTemplate() throws Exception {
        return new MongoTemplate(newdb1MongoDatabaseFactory(getNewDb1Props()));
    }

    @Bean(name ="newdb2MongoTemplate")
    public MongoTemplate newdb2MongoTemplate() throws Exception {
        return new MongoTemplate(newdb2MongoDatabaseFactory(getNewDb2Props()));
    }

    @Primary
    @Bean
    public MongoDatabaseFactory newdb1MongoDatabaseFactory(MongoProperties mongo) throws Exception {
        return new SimpleMongoClientDatabaseFactory(
                mongo.getUri()
        );
    }

    @Bean
    public MongoDatabaseFactory newdb2MongoDatabaseFactory(MongoProperties mongo) throws Exception {
        return new SimpleMongoClientDatabaseFactory(
                mongo.getUri()
        );
    }

}

相关问题