如何通过属性配置spring-data-mongodb以使用副本集

31

我目前正在写一个应用程序,它应该使用MongoDB的副本集。这是一个基于Spring Boot的应用程序,以下属性可完美地连接到一个服务器:

spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=demo

这对我的本地开发环境来说完全没问题。但是以后它应该针对MongoDB副本集运行,所以我必须提供至少2个,最好3个副本集种子,但我该如何使用属性来做到这一点?

我查看了这个页面:http://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html,但没有明确的属性用于副本集。提供一个逗号分隔的地址列表,如下:

spring.data.mongodb.host=127.0.0.1,127.0.1.1,127.0.2.1
spring.data.mongodb.uri=mongo://127.0.0.1,mongo://127.0.0.1:27018

(我尝试了一个接着一个的方法。)

这个也不起作用(事实上,它会产生一个异常,让Spring使用默认配置)。

我还尝试使用以下config.xml,但没有成功:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xmlns:context="http://www.springframework.org/schema/context"
          xmlns:mongo="http://www.springframework.org/schema/data/mongo"
          xsi:schemaLocation=
          "http://www.springframework.org/schema/context
          http://www.springframework.org/schema/context/spring-context-3.0.xsd
          http://www.springframework.org/schema/data/mongo
          http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd
          http://www.springframework.org/schema/beans
          http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <mongo:mongo id="replicaSetMongo" replica-set="127.0.0.1:27017,localhost:27018"/>

</beans>
我知道上面的配置略有不同,但我目前尝试的是获得一个异常,显示没有可到达的副本集节点。 你有什么想法或提示吗?

如果您正在使用Mongo Atlas,则此文章将会对您有所帮助 - https://www.opencodez.com/java/use-mongodb-atlas-with-spring-boot.htm - jmathewt
3个回答

23

我曾经遇到过类似的问题,深入研究了 MongoProperties::createMongoClient() 代码后发现,如果在配置文件中为spring.data.mongodb.hostspring.data.mongodb.portspring.data.mongodb.usernamespring.data.mongodb.password设置了任何值,该代码将忽略uri的值。

如果我把所有这些信息都放在URI中(并从属性文件中删除所有其他的spring.data.mongodb.*值),连接代码就能正常工作了。

最终URI属性设置如下:

mongodb://username:mypasswd@hostname1:27017,hostname2:27017,hostname3:27017/dbname

格式化URI值的文档在这里


谢谢您的评论,我完全忘记添加这个。实际上,如果设置了任何一个提到的值,URI 将被忽略。 - incredibleholg
请问您可以告诉我在这里添加身份验证数据库名称的位置吗? - Sameesh
连接到副本集时,默认情况下读取操作将从主节点进行,除非明确指定从次要节点读取,对吧? - Fernando
replset选项标志是否必须指定?如果未指定会发生什么? - Fernando

23

没有明确的支持,但您应该能够通过uri参数轻松配置。

我们实际上最近已经更新了文档


谢谢你的回答,Stephane。Spring Data Mongo的哪个版本支持这种配置属性? - incredibleholg
好的,我终于有时间来检查这个了。它似乎可以工作。但是日志信息对于集群并不是很清晰(希望我能找到一些时间来调查并记录问题)。无论如何,感谢您的快速帮助! - incredibleholg

9

将application.properties更改为:

spring.data.mongodb.host=server1
spring.data.mongodb.port=27017
spring.data.mongodb.authentication-database=system
spring.data.mongodb.database=database

...转换为以下内容:

spring.data.mongodb.uri=mongodb://username:password@server1:port,server2:port/database

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接