spring boot mongo多数据源配置

配置文件

## 第一个配置
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());
    }
}

你可能感兴趣的:(java)