Volg de onderstaande stappen om meerdere mongodb-gegevensbronnen in te stellen.
-
Definieer uw primaire en secundaire mongodb-eigenschappen zoals hieronder in application.properties, vervang ze alstublieft door uw db-gegevens:
######Primary Mongo DB######################## spring.data.mongodb.host=localhost spring.data.mongodb.database=primary spring.data.mongodb.port=27017 spring.data.mongodb.password=******* spring.data.mongodb.username=******* ###########Secondary MongoDB##################### mongodb.host=localhost mongodb.port=27017 mongodb.database=secondary mongodb.username=****** mongodb.password=******
-
Voeg nu meerdere Mongo Db-configuratie toe.
@Configuration public class MultipleMongoConfig { @Primary @Bean(name = "primary") @ConfigurationProperties(prefix = "spring.data.mongodb") public MongoProperties getPrimary() { return new MongoProperties(); } @Bean(name = "secondary") @ConfigurationProperties(prefix = "mongodb") public MongoProperties getSecondary() { return new MongoProperties(); } @Primary @Bean(name = "primaryMongoTemplate") public MongoTemplate primaryMongoTemplate() throws Exception { return new MongoTemplate(primaryFactory(getPrimary())); } @Bean(name = "secondaryMongoTemplate") public MongoTemplate secondaryMongoTemplate() throws Exception { return new MongoTemplate(secondaryFactory(getSecondary())); } @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()); }
}
-
Schakel nu
EnableMongoRepositories
in voor uw primaire een secundaire.Zorg ervoor dat ubasePackages = "com.example.springbootmultipledatasource.primary.repository"
wijzigt uw repository-pakket hier@Configuration @EnableMongoRepositories(basePackages = "com.example.springbootmultipledatasource.primary.repository", mongoTemplateRef = "primaryMongoTemplate") public class PrimaryMongoConfig { }
Secundaire Mongo-sjabloon:zorg ervoor dat u uw secundaire repository-pakket hier wijzigt basePackages = "com.example.springbootmultipledatasource.secondary.repository
@Configuration
@EnableMongoRepositories(basePackages = "com.example.springbootmultipledatasource.secondary.repository",
mongoTemplateRef = "secondaryMongoTemplate")
public class SecondaryMongoConfig {
}
Nu kunt u uw document, repository, service, controller maken en u bent klaar om te gaan. Hieronder is mijn projectstructuur die u kunt maken of die u anders kunt hebben.