【问题标题】:How to configure spring-data-mongodb to use a replica set via properties如何通过属性配置 spring-data-mongodb 以使用副本集
【发布时间】:2015-10-28 15:47:51
【问题描述】:

我目前正在编写一个应该使用 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>

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

有什么想法、提示吗?

【问题讨论】:

标签: java mongodb spring-boot spring-data-mongodb


【解决方案1】:

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

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

【讨论】:

  • 感谢您的回答斯蒂芬。哪个版本的 Spring Data Mongo 支持这种配置属性?
  • 好的,我终于有时间检查一下了。它似乎工作。但是关于集群的日志消息不是很清楚(希望我能找到一些时间来调查和记录问题)无论如何,感谢您的快速帮助!
【解决方案2】:

我遇到了类似的问题,我研究了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 值的文档是 here

【讨论】:

  • 感谢您的评论,我完全忘了添加这个。实际上,如果设置了任何提到的值,则 URI 将被忽略。
  • 你能告诉我在哪里添加认证数据库名称吗?
  • 当连接到副本集时,默认情况下将从主节点读取,除非明确指定从辅助节点读取?
  • 是否必须指定 replset 选项标志?如果不指定会怎样?
【解决方案3】:

从此更改 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

【讨论】:

    猜你喜欢
    • 2014-06-06
    • 1970-01-01
    • 2016-05-22
    • 1970-01-01
    • 2020-12-30
    • 1970-01-01
    • 1970-01-01
    • 2017-09-01
    • 1970-01-01
    相关资源
    最近更新 更多