spring: data: mongodb: host: 192.168.1.1:27017 username: test_user password: pass@123 database: tdb
這是spring-mongodb的配置,當mongodb使用了集群之后我嘗試着直接修改
host: 192.168.1.1:27017,192.168.1.2:27017,192.168.1.3:27017
啟動是沒問題,使用是直接報錯了UnknowHost,顯然這樣是不行的
查看了spring autorconfig的源碼
org.springframework.boot.autoconfigure.mongo.MongoProperties
private MongoClient createEmbeddedMongoClient(MongoClientOptions options, int port) { if (options == null) { options = MongoClientOptions.builder().build(); } String host = (this.host != null ? this.host : "localhost"); return new MongoClient(Collections.singletonList(new ServerAddress(host, port)), Collections.<MongoCredential>emptyList(), options); } private MongoClient createNetworkMongoClient(MongoClientOptions options) { if (hasCustomAddress() || hasCustomCredentials()) { if (this.uri != null) { throw new IllegalStateException("Invalid mongo configuration, " + "either uri or host/port/credentials must be specified"); } if (options == null) { options = MongoClientOptions.builder().build(); } List<MongoCredential> credentials = new ArrayList<MongoCredential>(); if (hasCustomCredentials()) { String database = (this.authenticationDatabase != null ? this.authenticationDatabase : getMongoClientDatabase()); credentials.add(MongoCredential.createCredential(this.username, database, this.password)); } String host = (this.host != null ? this.host : "localhost"); int port = (this.port != null ? this.port : DEFAULT_PORT); return new MongoClient( Collections.singletonList(new ServerAddress(host, port)), credentials, options); } // The options and credentials are in the URI return new MongoClient(new MongoClientURI(determineUri(), builder(options))); }
顯然這個配置提供了兩種配置方式createEmbeddedMongoClient和createNetworkMongoClient
createEmbeddedMongoClient中創建MongoClient的時候使用的是Collections.singletonList這不可能是集群環境的配置所以看了一下createNetworkMongoClient的代碼hasCustomAddress()和hasCustomCredentials()是是否有判斷username、password、host、port配置,如果有這些配置並且uri不為空就會直接報錯,也就是uri配置不能與其共存,host的配置方式又不能配置集群環境那么只能使用uri來實現集群配置了。
根據配置類上的文檔注釋嘗試着修改配置為 https://www.dianjilingqu.com/
spring: data: mongodb: uri: mongodb://test_user:pass%40123@192.168.1.1:27017,192.168.1.2:27017,192.168.1.3:27017/tdb
注意:username和password中含有“:”或“@”需要進行URLEncoder編碼