在开发过程中有的时候需要像mysql那样需要使用多个mongodb数据库。
可以使用mongodb配置使用多个mongotemplate
在pom.xml中引入
org.springframework.boot spring-boot-starter-data-mongodb
在配置文件中配置多个uri
spring.data.mongodb1.uri=mongodb://192.168.0.66/test1spring.data.mongodb2.uri=mongodb://192.168.0.66/test2
新建配置文件
@Configurationpublic class MongoConfig { @Value("${spring.data.mongodb1.uri}") private String mongodb1; @Value("${spring.data.mongodb2.uri}") private String mongodb2; @Bean public MongoMappingContext mongoMappingContext() { return new MongoMappingContext(); } /** * 配置mongodb1 */ @Bean public MappingMongoConverter mappingMongoConverter() throws UnknownHostException { DefaultDbRefResolver dbRefResolver = new DefaultDbRefResolver(this.mongoDbFactory1()); MappingMongoConverter converter = new MappingMongoConverter(dbRefResolver, this.mongoMappingContext()); converter.setTypeMapper(new DefaultMongoTypeMapper(null)); return converter; } @Bean @Primary public MongoDbFactory mongoDbFactory1() throws UnknownHostException { return new SimpleMongoDbFactory(new MongoClientURI(mongodb1)); } @Bean @Primary public MongoTemplate mongoTemplate1() throws UnknownHostException { return new MongoTemplate(this.mongoDbFactory1(), mappingMongoConverter()); } /** * 配置mongdodb2 */ @Bean public MongoDbFactory mongoDbFactory2() throws UnknownHostException { return new SimpleMongoDbFactory(new MongoClientURI(mongodb2)); } @Bean public MongoTemplate mongoTemplate2() throws UnknownHostException { return new MongoTemplate(this.mongoDbFactory2()); }}
测试文件中引入多个MongoTemplate
@RunWith(SpringRunner.class)@SpringBootTestpublic class DemoApplicationTests { @Resource MongoTemplate mongoTemplate1; @Resource MongoTemplate mongoTemplate2; @Test public void contextLoads() { User user = new User(); user.setUsername("sher"); mongoTemplate1.save(user); User user1 = new User(); user1.setUsername("java"); mongoTemplate2.save(user1); }}
测试结果: