SpringBoot-mongodb集群环境配置
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来实现集群配置了。
根据配置类上的文档注释尝试着修改配置为
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编码
上一篇:
通过多线程提高代码的执行效率例子
下一篇:
机器学习-LSTM中的几个参数理解