springboot+2個mongoTemplate

在開發過程當中有的時候須要像mysql那樣須要使用多個mongodb數據庫。java

可使用mongodb配置使用多個mongotemplatemysql

在pom.xml中引入spring

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

在配置文件中配置多個urisql

spring.data.mongodb1.uri=mongodb://192.168.0.66/test1
spring.data.mongodb2.uri=mongodb://192.168.0.66/test2

新建配置文件mongodb

@Configuration
public 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)
@SpringBootTest
public 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);
    }
}

測試結果:app

相關文章
相關標籤/搜索