SpringBoot中配置mongo多数据源
1.在配置文件中配置好需要连接的mongo数据源信息
spring.mongo.uri.primary: "mongodb://192.168.200.109:27017/testDatasource"
spring.mongo.uri.second: "mongodb://192.168.200.109:27016/testData"
2.在配置类中引用,并创建不同数据源的mongoTemplate
@Configuration
public class MongoConfig {
@Value("${spring.mongo.uri.primary}")
String primaryUri;
@Value("${spring.mongo.uri.second}")
String secondUri;
@Primary //设置为默认数据源
@Bean(name = "mongoTemplate")
public MongoTemplate primaryMongoTemplate() {
MongoDatabaseFactory primaryFactory = new SimpleMongoClientDatabaseFactory(primaryUri);
DbRefResolver dbRefResolver = new DefaultDbRefResolver(primaryFactory);
MappingMongoConverter converter = new MappingMongoConverter(dbRefResolver, new MongoMappingContext());
//设置在插入数据的时候不添加 _class 属性
converter.setTypeMapper(new DefaultMongoTypeMapper(null));
return new MongoTemplate(primaryFactory, converter);
}
@Bean(name = "secondMongoTemplate")
public MongoTemplate secondMongoTemplate() {
MongoDatabaseFactory secondFactory = new SimpleMongoClientDatabaseFactory(secondUri);
DbRefResolver dbRefResolver = new DefaultDbRefResolver(secondFactory);
MappingMongoConverter converter = new MappingMongoConverter(dbRefResolver, new MongoMappingContext());
converter.setTypeMapper(new DefaultMongoTypeMapper(null));
return new MongoTemplate(secondFactory, converter);
}
}
3.注意当引入了MongoDB依赖之后,根据自动装配的原理项目中会自动查找默认MongoDB的地址(localhost:27017),而本地没有开启Mongo所以连接失败,启动类上排除MongoDB 自动配置类即可
@SpringBootApplication(exclude = {
MongoAutoConfiguration.class,
MongoDataAutoConfiguration.class
})