有时候需要使用多个mongoTemplate访问两个不同的mongodb实例,此时(在spring-boot的情况下)无法使用默认配置,只能手动配了。
1、引入依赖(以spring-boot为例)
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
2、配置文件中配置两个mongodb uri(也可以配成两个host/port)
spring:
profiles: dev
data:
mongodb:
uri: mongodb://192.168.0.9:27017/log1DbName
mongodb2:
uri: mongodb://192.168.0.11:27017/log2DbName
3、配置文件出场:
@Configuration
public class MongoConfig{
//@Value("${mongo.host}")
@Value("${spring.data.mongodb.uri}")
private String MONGO_URI1;
@Value("${spring.data.mongodb2.uri}")
private String MONGO_URI2;
@Bean
public MongoMappingContext mongoMappingContext() {
MongoMappingContext mappingContext = new MongoMappingContext();
return mappingContext;
}
// ==================== 连接到 mongodb1 服务器 ======================================
@Bean //使用自定义的typeMapper去除写入mongodb时的“_class”字段
public MappingMongoConverter mappingMongoConverter1() throws Exception {
DefaultDbRefResolver dbRefResolver = new DefaultDbRefResolver(this.dbFactory1());
MappingMongoConverter converter = new MappingMongoConverter(dbRefResolver, this.mongoMappingContext());
converter.setTypeMapper(new DefaultMongoTypeMapper(null));
return converter;
}
@Bean
@Primary
public MongoDbFactory dbFactory1() throws UnknownHostException {
return new SimpleMongoDbFactory(new MongoClientURI(MONGO_URI1));
}
@Bean
@Primary
public MongoTemplate mongoTemplate1() throws Exception {
return new MongoTemplate(this.dbFactory1(), this.mappingMongoConverter1());
}
// ===================== 连接到 mongodb2 服务器 =================================
//不需要去除写入mongodb时的“_class”字段
/* //可以使用Mongo或MongoDbFactory两种对象进行配置
@Bean
public Mongo mongo2() throws Exception {
return new MongoClient(new MongoClientURI(MONGO_DATA_SYNC_URI));
}
@Bean
public MongoTemplate mongoTemplate2() throws Exception {
return new MongoTemplate(mongo2(), "log2DbName");
}
*/
@Bean
public MongoDbFactory dbFactory2() throws UnknownHostException {
return new SimpleMongoDbFactory(new MongoClientURI(MONGO_URI2));
}
@Bean
public MongoTemplate mongoTemplate2() throws Exception {
return new MongoTemplate(dbFactory2());
}
}
4、使用方法:使用@Resource注解根据名字注入两个不同的mongoTemplate
@Resource
private MongoTemplate mongoTemplate1;
@Resource
private MongoTemplate mongoTemplate2;
@Test
public void mongoTemplateTest(){
PVUV pvuv = new PVUV();
pvuv.setDate(LocalDate.now());
pvuv.setPv(1000);
pvuv.setUv(200);
mongoTemplate1.save(pvuv, "pvUvCollection");
mongoTemplate2.save(pvuv, "pvUvCollection");
}