springboot MongoDB 主从 多数据源

上一篇,我写了关于用一个map管理mongodb多个数据源(每个数据源,只有单例)的内容。

springboot mongodb 配置多数据源

临到部署到阿里云的测试环境,发现还需要考虑一下主从的问题,阿里云买的数据库,不是说让你无感知的,而是给了2个url,一个主一个从的,这个只能我们在java代码里初始化实例的时候,配置进去。

庆幸的是,实例化MongoClient的时候,初始化方法里,有考虑集群的这种情况。

所以从单例改主从,只需要把原来的以String connectionString参数的构造方法,

MongoClient client = MongoClients.create(String类型的mongoUrl地址);

改为使用MongoClientSettings参数的构造方法,即可。

代码如下改动:

//账号密码认证
MongoCredential credentia =
          MongoCredential.createScramSha1Credential(
              用户名, mongo权限验证库-默认是admin, 用户密码.toCharArray());
//将主从地址以数组的形式进行传入,第一个是主,除了第一个之外的是从库
List<ServerAddress> serverList = new ArrayList<>();
serverList.add(new ServerAddress(主域名, 主端口));
//serverList.add(new ServerAddress(从域名, 从端口));
MongoClientSettings settings =
          MongoClientSettings.builder()
              .applyToClusterSettings(builder -> builder.hosts(serverList).这里还可以设置集群的各种属性,自己决定吧)
              .credential(credentia)
              .build();  
MongoClient client = MongoClients.create(settings);

然后使用MongoTemplate的下列初始化方法,即可得到指定主从的template

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Spring Boot中,我们可以使用MongoDB作为数据库,并且可以配置多个MongoDB数据源。为了实现这个目标,我们需要在配置文件中添加多个MongoDB数据源的URI,然后在代码中根据不同的数据源配置生成不同的MongoTemplate。具体实现可以参考以下步骤: 1.在配置文件中添加多个MongoDB数据源的URI,例如: spring.data.mongodb.uri=mongodb://localhost:27017/primary spring.data.mongodb.other.uri=mongodb://localhost:27017/other 2.创建一个配置类MultipleMongoConfig,根据不同的数据源配置生成不同的MongoTemplate,例如: @Configuration public class MultipleMongoConfig { @Value("${spring.data.mongodb.uri}") private String primaryUri; @Value("${spring.data.mongodb.other.uri}") private String otherUri; @Primary @Bean(name = "primaryMongoTemplate") public MongoTemplate primaryMongoTemplate() throws Exception { SimpleMongoClientDbFactory simpleMongoClientDbFactory = new SimpleMongoClientDbFactory(primaryUri); return new MongoTemplate(simpleMongoClientDbFactory); } @Bean(name = "otherMongoTemplate") public MongoTemplate otherMongoTemplate() throws Exception { SimpleMongoClientDbFactory simpleMongoClientDbFactory = new SimpleMongoClientDbFactory(otherUri); return new MongoTemplate(simpleMongoClientDbFactory); } } 3.创建一个主数据源配置类PrimaryMongoConfig,配置主数据源的MongoTemplate,例如: @Configuration @ConfigurationProperties(prefix="spring.data.mongodb") public class PrimaryMongoConfig extends AbstractMongoConfig{ @Primary @Bean(name="mongoTemplate") @Override public MongoTemplate getMongoTemplate() { return new MongoTemplate(mongoDbFactory()); } } 以上就是使用Spring Boot配置多个MongoDB数据源的方法。如果你需要使用更多的数据源,只需要在配置文件中添加更多的URI,并在代码中生成对应的MongoTemplate即可。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

rgbhi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值