這是我springboot連接 MongoDB 配置
spring:
data:
mongodb:
uri: mongodb://192.168.1.143:9085/test,mongodb://192.168.1.144:9085/test,mongodb://192.168.1.145:9085/test
連接MongoDB 集羣是出現
java.lang.IllegalArgumentException: The connection string contains an invalid host 'mongodb://39.97.113.214:9085'. Reserved characters such as ':' must be escaped according RFC 2396. Any IPv6 address literal must be enclosed in '[' and ']' according to RFC 2732.
看到RFC 2732 有點懵逼,這是啥玩意,百度一下,發現這是“Internet 官方協議標準”(STD 1),給出的解釋是在文字中IPv6 地址定義的文本表示與 URL 不直接兼容。因爲兩者使用了 “:”和“.” 作爲分隔符。他們要求要在URL中使用文字IPv6地址,文字地址應包含在“[”和“]”字符中,詳細解釋請看1999年12月發佈的URL中的文字IPv6地址的格式備忘錄
配置文件修改如下
spring:
data:
mongodb:
uri: mongodb://[192.168.1.143:9085]/test,[192.168.1.144:9085]/test,[192.168.1.145:9085]/test
MongoDB源碼也給出了示例的:
**
* <p>Represents a <a href="http://www.mongodb.org/display/DOCS/Connections">Connection String</a>. The Connection String describes the
* hosts to be used and options.</p>
*
* <p>The format of the Connection String is:</p>
* <pre>
* mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database.collection][?options]]
* </pre>
* <ul>
* <li>{@code mongodb://} is a required prefix to identify that this is a string in the standard connection format.</li>
* <li>{@code username:password@} are optional. If given, the driver will attempt to login to a database after
* connecting to a database server. For some authentication mechanisms, only the username is specified and the password is not,
* in which case the ":" after the username is left off as well</li>
* <li>{@code host1} is the only required part of the connection string. It identifies a server address to connect to.
* Support for Unix domain sockets was added in 3.7. Note: The path must be urlencoded eg: {@code mongodb://%2Ftmp%2Fmongodb-27017.sock}
* and the {@code jnr.unixsocket} library installed.
* </li>
* <li>{@code :portX} is optional and defaults to :27017 if not provided.</li>
* <li>{@code /database} is the name of the database to login to and thus is only relevant if the
* {@code username:password@} syntax is used. If not specified the "admin" database will be used by default.</li>
* <li>{@code ?options} are connection options. Note that if {@code database} is absent there is still a {@code /}
* required between the last host and the {@code ?} introducing the options. Options are name=value pairs and the pairs
* are separated by "&". For backwards compatibility, ";" is accepted as a separator in addition to "&",
* but should be considered as deprecated.</li>
* </ul>
* <p>An alternative format, using the mongodb+srv protocol, is:
* <pre>
* mongodb+srv://[username:password@]host[/[database][?options]]
* </pre>