Følg venligst nedenstående trin for at konfigurere flere mongodb-datakilder.
-
Definer dine primære og sekundære mongodb-egenskaber som nedenfor i application.properties, udskift venligst dine db-oplysninger med dem:
######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=******
-
Tilføj nu Multiple Mongo Db Configuration..
@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()); }
}
-
Aktiver nu
EnableMongoRepositories
for din primære og sekundære. Sørg for at ændrebasePackages = "com.example.springbootmultipledatasource.primary.repository"
din depotpakke her@Configuration @EnableMongoRepositories(basePackages = "com.example.springbootmultipledatasource.primary.repository", mongoTemplateRef = "primaryMongoTemplate") public class PrimaryMongoConfig { }
Sekundær Mongo-skabelon:Sørg for at ændre din sekundære repository-pakke her basePackages = "com.example.springbootmultipledatasource.secondary.repository
@Configuration
@EnableMongoRepositories(basePackages = "com.example.springbootmultipledatasource.secondary.repository",
mongoTemplateRef = "secondaryMongoTemplate")
public class SecondaryMongoConfig {
}
Nu kan du oprette dit dokument, arkiv, service, controller, og du er godt i gang. Nedenfor er min projektstruktur, du kan oprette eller have anderledes.