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!
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于