springboot中设置多个MongoDB数据源

springboot中 如果配置打个数据源 默认是读取host port这些 没有读取url

spring:
  data:
    mongodb:
      username: test
      password: test
      port: 8086
      host: 127.0.0.1
      authentication-database: admin
      database: mongo_test

但是如果想配置多个数据源 需要用url的方式才能满足需求,为了配置多个MongoDB的数据源,网上找了很多资料都不好用,特意记录在这里 方便后面的兄弟姐妹使用
首先建立一个抽象的总类

@Data
public abstract class AbstractMongoConfig {
    String url;
    String database;
    public MongoDbFactory mongoDbFactory() throws Exception {
        return new SimpleMongoDbFactory(new MongoClient(new MongoClientURI(url)), database);
    }
    public abstract  MongoTemplate getMongoTemplate() throws Exception;
}

然后配置分数据源 如

@Configuration
@ConfigurationProperties(prefix = "spring.data.mongodb.mango-account")
public class AccountConfig extends AbstractMongoConfig{
    @Override
    @Primary
    @Bean(name="accountMongoTemplate")
    public MongoTemplate getMongoTemplate() throws Exception {
        return new MongoTemplate(mongoDbFactory());
    }
}

这样就配置成功啦.如果还没有配置成功的同学 可以点一下 看看源码 我就是这样配的

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容