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

How to configure spring-data-mongodb to use a replica set via properties

我目前正在编写一个应用程序,它应该使用 MongoDB 的副本集。它是一个 Spring 基于引导的应用程序,并且以下属性非常适合连接到一台服务器:

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>

我知道上面的配置略有不同,但我目前正在尝试的是获取一个异常,该异常显示无法访问副本集节点。

有什么想法、提示吗?

没有明确的支持,不。但是您应该能够通过 uri 参数进行配置。

我们实际上最近更新了 the documentation

我遇到了类似的问题,我深入研究了 MongoProperties::createMongoClient() 代码,发现如果为 spring.data.mongodb.hostspring.data.mongodb.port 配置了任何值,代码会忽略 uri 值, spring.data.mongodb.usernamespring.data.mongodb.password

如果我将所有这些信息放在 URI 中(并从 属性 文件中删除所有其他 spring.data.mongodb.* 值),连接代码就会起作用。

URI 属性 设置最终如下所示:

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

格式化 URI 值的文档是 here

从这里更改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