Polish 'Allow multiple hosts to be set in MongoProperties'

See gh-32125
This commit is contained in:
Phillip Webb
2022-08-23 19:10:50 -07:00
parent e0d40009f3
commit 6db88e12c8
3 changed files with 25 additions and 19 deletions

View File

@@ -61,6 +61,13 @@ public class MongoProperties {
*/
private Integer port = null;
/**
* Additional server hosts. Cannot be set with URI or if 'host' is not specified.
* Additional hosts will use the default mongo port of 27017, if you want to use a
* different port you can use the "host:port" syntax.
*/
private List<String> additionalHosts;
/**
* Mongo database URI. Overrides host, port, username, password, and database.
*/
@@ -108,11 +115,6 @@ public class MongoProperties {
*/
private Boolean autoIndexCreation;
/**
* List of additional hosts to connect with different hosts in a replica set.
*/
private List<String> additionalHosts;
public String getHost() {
return this.host;
}

View File

@@ -25,6 +25,7 @@ import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import org.springframework.core.Ordered;
import org.springframework.util.CollectionUtils;
/**
* A {@link MongoClientSettingsBuilderCustomizer} that applies properties from a
@@ -64,22 +65,17 @@ public class MongoPropertiesClientSettingsBuilderCustomizer implements MongoClie
if (this.properties.getHost() != null || this.properties.getPort() != null) {
String host = getOrDefault(this.properties.getHost(), "localhost");
int port = getOrDefault(this.properties.getPort(), MongoProperties.DEFAULT_PORT);
ServerAddress serverAddress = new ServerAddress(host, port);
List<ServerAddress> serverAddressList = new ArrayList<>(List.of(serverAddress));
applyAdditionalHosts(serverAddressList);
settings.applyToClusterSettings((cluster) -> cluster.hosts(serverAddressList));
List<ServerAddress> serverAddresses = new ArrayList<>();
serverAddresses.add(new ServerAddress(host, port));
if (!CollectionUtils.isEmpty(this.properties.getAdditionalHosts())) {
this.properties.getAdditionalHosts().stream().map(ServerAddress::new).forEach(serverAddresses::add);
}
settings.applyToClusterSettings((cluster) -> cluster.hosts(serverAddresses));
return;
}
settings.applyConnectionString(new ConnectionString(MongoProperties.DEFAULT_URI));
}
private void applyAdditionalHosts(List<ServerAddress> serverAddressList) {
if (this.properties.getAdditionalHosts() != null && !this.properties.getAdditionalHosts().isEmpty()) {
this.properties.getAdditionalHosts()
.forEach((additionalHost) -> serverAddressList.add(new ServerAddress(additionalHost)));
}
}
private void applyCredentials(MongoClientSettings.Builder builder) {
if (this.properties.getUri() == null && this.properties.getUsername() != null
&& this.properties.getPassword() != null) {