有時候需要使用多個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、設定檔出場:
@Configurationpublic 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
@Resourceprivate MongoTemplate mongoTemplate1;@Resourceprivate MongoTemplate mongoTemplate2;@Testpublic void mongoTemplateTest(){ PVUV pvuv = new PVUV(); pvuv.setDate(LocalDate.now()); pvuv.setPv(1000); pvuv.setUv(200); mongoTemplate1.save(pvuv, "pvUvCollection"); mongoTemplate2.save(pvuv, "pvUvCollection");}