Sometimes it is necessary to use multiple mongotemplate to access two different MongoDB instances, at which point the default configuration cannot be used (in spring-boot case) and can only be manually matched. 1. Introducing dependence (take spring-boot as an example)
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId> Spring-boot-starter-data-mongodb</artifactid>
</dependency>
2, configuration file to configure two MongoDB URI (also can be matched to two 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 file appearance:
@Configuration public class mongoconfig{//@Value ("${mongo.host}") @Value ("${spring.data.mongodb.uri}") Private S
Tring Mongo_uri1;
@Value ("${spring.data.mongodb2.uri}") Private String mongo_uri2; @Bean public Mongomappingcontext Mongomappingcontext () {Mongomappingcontext mappingcontext = new Mongomappingcon
Text ();
return mappingcontext; //==================== Connect to MONGODB1 server ====================================== @Bean//Use custom typemapper to remove write Mong The "_class" field at ODB is public mappingmongoconverter mappingMongoConverter1 () throws Exception {Defaultdbrefresolver DbR
Efresolver = 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.db
Factory1 (), This.mappingmongoconverter1 ()); }//===================== connect to MONGODB2 server =================================//No need to remove "_class" field when writing to MongoDB///can use M Ongo or Mongodbfactory Two objects are configured @Bean public Mongo Mongo2 () throws Exception {return new mongoclient (new MONGOCLI
Enturi (Mongo_data_sync_uri)); @Bean public Mongotemplate MongoTemplate2 () throws Exception {return new Mongotemplate (Mongo2 (), Log2dbnam
E "); } */@Bean public mongodbfactory DbFactory2 () throws Unknownhostexception {return new Simplemongodbfactory (n
EW Mongoclienturi (MONGO_URI2));
@Bean public Mongotemplate MongoTemplate2 () throws Exception {return new Mongotemplate (DbFactory2 ()); }
}
4, use method: use @resource annotation According to the name inject two different 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 ();
Mongotemplate1.save (Pvuv, "pvuvcollection");
Mongotemplate2.save (Pvuv, "pvuvcollection");
}