springboot项目配置多个mongo数据源的方法 有更新!

  , ,
评论 • 131 浏览

    1、在yml文件中指定mongodb的数据

    mongodb:
        primary:
            host: xxx.xxx.xxx.xxx
            port: 27017
            database: name1
        secondary:
            host: xxx.xxx.xxx.xxx
            port: 27017
            database: name2
    

    2、新建MultipleMongoConfig文件

    @Configuration
    @ConfigurationProperties(prefix = "mongodb")
    public class MultipleMongoConfig {
    
        private MongoProperties primary = new MongoProperties();
     private MongoProperties secondary = new MongoProperties();
    
      @Primary
     @Bean(name = "TemplateA")
        public MongoTemplate primaryMongoTemplate() throws Exception {
            return new MongoTemplate(primaryFactory(primary));
      }
    
        @Bean(name = "TemplateB")
        public MongoTemplate secondaryMongoTemplate() throws Exception {
            return new MongoTemplate(secondaryFactory(secondary));
      }
    
      @Bean
     @Primary  public MongoDbFactory primaryFactory(final MongoProperties mongo) throws Exception {
            return new SimpleMongoDbFactory(new MongoClient(mongo.getHost(), mongo.getPort()),
      mongo.getDatabase());
      }
    
        @Bean
      public MongoDbFactory secondaryFactory(final MongoProperties mongo) throws Exception {
            return new SimpleMongoDbFactory(new MongoClient(mongo.getHost(), mongo.getPort()),
      mongo.getDatabase());
      }
    
    
      public MongoProperties getPrimary() {
            return primary;
      }
    
        public void setPrimary(MongoProperties primary) {
            this.primary = primary;
      }
    
        public MongoProperties getSecondary() {
            return secondary;
      }
    
        public void setSecondary(MongoProperties secondary) {
            this.secondary = secondary;
      }
    }
    

    3、为每一个数据源创建一个Configuration

    @Configuration
    @EnableMongoRepositories(basePackages = "repository所在的包名",
      mongoTemplateRef = "TemplateA(上面取的对应的bean名字)")
    public class TemplateAMongoConfiguration {
    }
    
    @Configuration
    @EnableMongoRepositories(basePackages = "repository所在的包名",
      mongoTemplateRef = "TemplateB(上面取的对应的bean名字)")
    public class TemplateBMongoConfiguration {
    }
    

    4、使用

    @Autowired
    @Qualifier("TemplateA")
    private MongoTemplate mongoTemplate;
    

    over!

    版权声明:本文为博主原创文章,欢迎大家转载,但需保留文章链接。个人博客地址:http://www.wenboblogs.cn
    评论
    validate