SpringBoot中配置mongo多数据源

SpringBoot中配置mongo多数据源

1.在配置文件中配置好需要连接的mongo数据源信息

spring.mongo.uri.primary: "mongodb://192.168.200.109:27017/testDatasource"
spring.mongo.uri.second: "mongodb://192.168.200.109:27016/testData"

2.在配置类中引用,并创建不同数据源的mongoTemplate

@Configuration
public class MongoConfig {

    @Value("${spring.mongo.uri.primary}")
    String primaryUri;
    @Value("${spring.mongo.uri.second}")
    String secondUri;

    @Primary //设置为默认数据源
    @Bean(name = "mongoTemplate") 
    public MongoTemplate primaryMongoTemplate() {
        MongoDatabaseFactory primaryFactory = new SimpleMongoClientDatabaseFactory(primaryUri);
        DbRefResolver dbRefResolver = new DefaultDbRefResolver(primaryFactory);
        MappingMongoConverter converter = new MappingMongoConverter(dbRefResolver, new MongoMappingContext());
        //设置在插入数据的时候不添加 _class 属性
        converter.setTypeMapper(new DefaultMongoTypeMapper(null));
        return new MongoTemplate(primaryFactory, converter);
    }

    @Bean(name = "secondMongoTemplate")
    public MongoTemplate secondMongoTemplate() {
        MongoDatabaseFactory secondFactory = new SimpleMongoClientDatabaseFactory(secondUri);
        DbRefResolver dbRefResolver = new DefaultDbRefResolver(secondFactory);
        MappingMongoConverter converter = new MappingMongoConverter(dbRefResolver, new MongoMappingContext());
        converter.setTypeMapper(new DefaultMongoTypeMapper(null));
        return new MongoTemplate(secondFactory, converter);
    }
}

3.注意当引入了MongoDB依赖之后,根据自动装配的原理项目中会自动查找默认MongoDB的地址(localhost:27017),而本地没有开启Mongo所以连接失败,启动类上排除MongoDB 自动配置类即可

@SpringBootApplication(exclude = {
        MongoAutoConfiguration.class,
        MongoDataAutoConfiguration.class
})
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值