spring boot mongo多数据源配置

允我心安 提交于 2020-01-25 07:45:03

配置文件

## 第一个配置
spring.data.mongodb.first.database=idisback
spring.data.mongodb.first.uri=mongodb://yingfuroot:yingfurootpwd@192.168.104.40:27017/admin
spring.data.mongodb.firs.username=yingfuroot
spring.data.mongodb.firs.password=yingfurootpwd
spring.data.mongodb.firs.authenticationDatabase=admin
## 第二个配置
spring.data.mongodb.second.database=handle
spring.data.mongodb.second.uri=192.168.104.39:27017
@Configuration
public class MultipleMongoProperties {

    @Bean(name = "firstMongoProperties")
    @Primary
    @ConfigurationProperties(prefix = "spring.data.mongodb.first")
    public MongoProperties firstMongoProperties() {
        System.out.println("-------------------- statisMongoProperties init ---------------------");
        return new MongoProperties();
    }

    @Bean(name = "secondMongoProperties")
    @ConfigurationProperties(prefix = "spring.data.mongodb.second")
    public MongoProperties secondMongoProperties() {
        System.out.println("-------------------- listMongoProperties init ---------------------");
        return new MongoProperties();
    }
}
@Configuration
@EnableMongoRepositories(basePackages = "cn.teleinfo.snms.data.repository.first", mongoTemplateRef = "firstMongo")
public class FirstMongoTemplate {

    @Autowired
    @Qualifier("firstMongoProperties")
    private MongoProperties mongoProperties;

    @Primary
    @Bean(name = "firstMongo")
    public MongoTemplate firstMongoTemplate() throws Exception {
        return new MongoTemplate(firstFactory(this.mongoProperties));
    }

    @Bean
    @Primary
    public MongoDbFactory firstFactory(MongoProperties mongoProperties) throws Exception {
        return new SimpleMongoDbFactory(new MongoClient(new MongoClientURI(mongoProperties.getUri())), mongoProperties.getDatabase());
    }
}

@Configuration
@EnableMongoRepositories(basePackages = "cn.teleinfo.snms.data.repository.second", mongoTemplateRef = "secondMongo")
public class SecondMongoTemplate {

    @Autowired
    @Qualifier("secondMongoProperties")
    private MongoProperties mongoProperties;

    @Bean(name = "secondMongo")
    public MongoTemplate secondTemplate() throws Exception {
        return new MongoTemplate(secondFactory(this.mongoProperties));
    }

    @Bean
    public MongoDbFactory secondFactory(MongoProperties mongoProperties) throws Exception {
        ServerAddress serverAdress = new ServerAddress(mongoProperties.getUri());
        return new SimpleMongoDbFactory(new MongoClient(serverAdress), mongoProperties.getDatabase());
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!