Search in sources :

Example 16 with ClusterSettings

use of com.mongodb.connection.ClusterSettings in project mongo-java-driver by mongodb.

the class LoadBalancedClusterTest method shouldSelectServerAsynchronouslyWhenThereIsSRVLookup.

@Test
public void shouldSelectServerAsynchronouslyWhenThereIsSRVLookup() {
    // given
    String srvHostName = "foo.bar.com";
    ServerAddress resolvedServerAddress = new ServerAddress("host1");
    ClusterableServer expectedServer = mock(ClusterableServer.class);
    ClusterSettings clusterSettings = ClusterSettings.builder().mode(ClusterConnectionMode.LOAD_BALANCED).srvHost(srvHostName).build();
    ClusterableServerFactory serverFactory = mockServerFactory(resolvedServerAddress, expectedServer);
    DnsSrvRecordMonitorFactory dnsSrvRecordMonitorFactory = mock(DnsSrvRecordMonitorFactory.class);
    when(dnsSrvRecordMonitorFactory.create(eq(srvHostName), eq(clusterSettings.getSrvServiceName()), any())).thenAnswer(invocation -> new TestDnsSrvRecordMonitor(invocation.getArgument(2)));
    cluster = new LoadBalancedCluster(new ClusterId(), clusterSettings, serverFactory, dnsSrvRecordMonitorFactory);
    // when
    FutureResultCallback<ServerTuple> callback = new FutureResultCallback<>();
    cluster.selectServerAsync(mock(ServerSelector.class), callback);
    ServerTuple serverTuple = callback.get();
    // then
    assertServerTupleExpectations(resolvedServerAddress, expectedServer, serverTuple);
}
Also used : FutureResultCallback(com.mongodb.async.FutureResultCallback) ClusterSettings(com.mongodb.connection.ClusterSettings) ClusterId(com.mongodb.connection.ClusterId) ServerAddress(com.mongodb.ServerAddress) ServerSelector(com.mongodb.selector.ServerSelector) RepeatedTest(org.junit.jupiter.api.RepeatedTest) Test(org.junit.jupiter.api.Test)

Example 17 with ClusterSettings

use of com.mongodb.connection.ClusterSettings in project mongo-java-driver by mongodb.

the class LoadBalancedClusterTest method shouldTimeoutSelectServerWhenThereIsSRVLookupException.

@Test
public void shouldTimeoutSelectServerWhenThereIsSRVLookupException() {
    // given
    String srvHostName = "foo.bar.com";
    ServerAddress resolvedServerAddress = new ServerAddress("host1");
    ClusterableServer expectedServer = mock(ClusterableServer.class);
    ClusterSettings clusterSettings = ClusterSettings.builder().serverSelectionTimeout(10, MILLISECONDS).mode(ClusterConnectionMode.LOAD_BALANCED).srvHost(srvHostName).build();
    ClusterableServerFactory serverFactory = mockServerFactory(resolvedServerAddress, expectedServer);
    DnsSrvRecordMonitorFactory dnsSrvRecordMonitorFactory = mock(DnsSrvRecordMonitorFactory.class);
    when(dnsSrvRecordMonitorFactory.create(eq(srvHostName), eq(clusterSettings.getSrvServiceName()), any())).thenAnswer(invocation -> new TestDnsSrvRecordMonitor(invocation.getArgument(2)).sleepTime(Duration.ofMillis(1)).exception(new MongoConfigurationException("Unable to resolve SRV record")));
    cluster = new LoadBalancedCluster(new ClusterId(), clusterSettings, serverFactory, dnsSrvRecordMonitorFactory);
    MongoTimeoutException exception = assertThrows(MongoTimeoutException.class, () -> cluster.selectServer(mock(ServerSelector.class)));
    assertEquals("Timed out after 10 ms while waiting to resolve SRV records for foo.bar.com. " + "Resolution exception was 'com.mongodb.MongoConfigurationException: Unable to resolve SRV record'", exception.getMessage());
}
Also used : MongoConfigurationException(com.mongodb.MongoConfigurationException) ClusterSettings(com.mongodb.connection.ClusterSettings) ClusterId(com.mongodb.connection.ClusterId) ServerAddress(com.mongodb.ServerAddress) MongoTimeoutException(com.mongodb.MongoTimeoutException) RepeatedTest(org.junit.jupiter.api.RepeatedTest) Test(org.junit.jupiter.api.Test)

Example 18 with ClusterSettings

use of com.mongodb.connection.ClusterSettings in project mongo-java-driver by mongodb.

the class LoadBalancedClusterTest method shouldSelectServerWhenThereIsNoSRVLookup.

@Test
public void shouldSelectServerWhenThereIsNoSRVLookup() {
    // given
    ServerAddress serverAddress = new ServerAddress("host1");
    ClusterableServer expectedServer = mock(ClusterableServer.class);
    ClusterSettings clusterSettings = ClusterSettings.builder().mode(ClusterConnectionMode.LOAD_BALANCED).hosts(Collections.singletonList(serverAddress)).build();
    ClusterableServerFactory serverFactory = mockServerFactory(serverAddress, expectedServer);
    cluster = new LoadBalancedCluster(new ClusterId(), clusterSettings, serverFactory, mock(DnsSrvRecordMonitorFactory.class));
    // when
    ServerTuple serverTuple = cluster.selectServer(mock(ServerSelector.class));
    // then
    assertServerTupleExpectations(serverAddress, expectedServer, serverTuple);
    // when
    FutureResultCallback<ServerTuple> callback = new FutureResultCallback<>();
    cluster.selectServerAsync(mock(ServerSelector.class), callback);
    serverTuple = callback.get();
    // then
    assertServerTupleExpectations(serverAddress, expectedServer, serverTuple);
}
Also used : FutureResultCallback(com.mongodb.async.FutureResultCallback) ServerSelector(com.mongodb.selector.ServerSelector) ClusterSettings(com.mongodb.connection.ClusterSettings) ClusterId(com.mongodb.connection.ClusterId) ServerAddress(com.mongodb.ServerAddress) RepeatedTest(org.junit.jupiter.api.RepeatedTest) Test(org.junit.jupiter.api.Test)

Example 19 with ClusterSettings

use of com.mongodb.connection.ClusterSettings in project mongo-java-driver by mongodb.

the class LoadBalancedClusterTest method shouldNotInitServerAfterClosing.

@Test
void shouldNotInitServerAfterClosing() {
    // prepare mocks
    ClusterSettings clusterSettings = ClusterSettings.builder().mode(ClusterConnectionMode.LOAD_BALANCED).srvHost("foo.bar.com").build();
    ClusterableServerFactory serverFactory = mock(ClusterableServerFactory.class);
    when(serverFactory.getSettings()).thenReturn(mock(ServerSettings.class));
    DnsSrvRecordMonitorFactory srvRecordMonitorFactory = mock(DnsSrvRecordMonitorFactory.class);
    when(srvRecordMonitorFactory.create(any(), eq(clusterSettings.getSrvServiceName()), any(DnsSrvRecordInitializer.class))).thenReturn(mock(DnsSrvRecordMonitor.class));
    ArgumentCaptor<DnsSrvRecordInitializer> serverInitializerCaptor = ArgumentCaptor.forClass(DnsSrvRecordInitializer.class);
    // create `cluster` and capture its `DnsSrvRecordInitializer` (server initializer)
    LoadBalancedCluster cluster = new LoadBalancedCluster(new ClusterId(), clusterSettings, serverFactory, srvRecordMonitorFactory);
    verify(srvRecordMonitorFactory, times(1)).create(any(), eq(clusterSettings.getSrvServiceName()), serverInitializerCaptor.capture());
    // close `cluster`, call `DnsSrvRecordInitializer.initialize` and check that it does not result in creating a `ClusterableServer`
    cluster.close();
    serverInitializerCaptor.getValue().initialize(Collections.singleton(new ServerAddress()));
    verify(serverFactory, never()).create(any(), any());
}
Also used : ClusterSettings(com.mongodb.connection.ClusterSettings) ClusterId(com.mongodb.connection.ClusterId) ServerSettings(com.mongodb.connection.ServerSettings) ServerAddress(com.mongodb.ServerAddress) RepeatedTest(org.junit.jupiter.api.RepeatedTest) Test(org.junit.jupiter.api.Test)

Example 20 with ClusterSettings

use of com.mongodb.connection.ClusterSettings in project spring-data-mongodb by spring-projects.

the class MongoClientFactoryBean method computeClientSetting.

/**
 * Create {@link MongoClientSettings} based on configuration and priority (lower is better).
 * <ol>
 * <li>{@link MongoClientFactoryBean#mongoClientSettings}</li>
 * <li>{@link MongoClientFactoryBean#connectionString}</li>
 * <li>default {@link MongoClientSettings}</li>
 * </ol>
 *
 * @since 3.0
 */
protected MongoClientSettings computeClientSetting() {
    if (connectionString != null && (StringUtils.hasText(host) || port != null)) {
        throw new IllegalStateException("ConnectionString and host/port configuration exclude one another!");
    }
    ConnectionString connectionString = this.connectionString != null ? this.connectionString : new ConnectionString(String.format("mongodb://%s:%s", getOrDefault(host, ServerAddress.defaultHost()), getOrDefault(port, "" + ServerAddress.defaultPort())));
    Builder builder = MongoClientSettings.builder().applyConnectionString(connectionString);
    builder.uuidRepresentation(UuidRepresentation.JAVA_LEGACY);
    if (mongoClientSettings != null) {
        MongoClientSettings defaultSettings = MongoClientSettings.builder().build();
        SslSettings sslSettings = mongoClientSettings.getSslSettings();
        ClusterSettings clusterSettings = mongoClientSettings.getClusterSettings();
        ConnectionPoolSettings connectionPoolSettings = mongoClientSettings.getConnectionPoolSettings();
        SocketSettings socketSettings = mongoClientSettings.getSocketSettings();
        ServerSettings serverSettings = mongoClientSettings.getServerSettings();
        builder = // 
        builder.applicationName(computeSettingsValue(defaultSettings.getApplicationName(), mongoClientSettings.getApplicationName(), // 
        connectionString.getApplicationName())).applyToSslSettings(settings -> {
            applySettings(settings::enabled, computeSettingsValue(SslSettings::isEnabled, defaultSettings.getSslSettings(), sslSettings, connectionString.getSslEnabled()));
            applySettings(settings::invalidHostNameAllowed, (computeSettingsValue(SslSettings::isInvalidHostNameAllowed, defaultSettings.getSslSettings(), sslSettings, connectionString.getSslInvalidHostnameAllowed())));
            settings.context(sslSettings.getContext());
        }).applyToClusterSettings(settings -> {
            applySettings(settings::hosts, computeSettingsValue(ClusterSettings::getHosts, defaultSettings.getClusterSettings(), clusterSettings, connectionString.getHosts().stream().map(ServerAddress::new).collect(Collectors.toList())));
            applySettings(settings::requiredReplicaSetName, computeSettingsValue(ClusterSettings::getRequiredReplicaSetName, defaultSettings.getClusterSettings(), clusterSettings, connectionString.getRequiredReplicaSetName()));
            applySettings(settings::srvHost, computeSettingsValue(ClusterSettings::getSrvHost, defaultSettings.getClusterSettings(), clusterSettings, null));
            applySettings(settings::mode, computeSettingsValue(ClusterSettings::getMode, defaultSettings.getClusterSettings(), clusterSettings, null));
            applySettings(it -> settings.localThreshold(it.longValue(), TimeUnit.MILLISECONDS), computeSettingsValue((ClusterSettings it) -> it.getLocalThreshold(TimeUnit.MILLISECONDS), defaultSettings.getClusterSettings(), clusterSettings, connectionString.getLocalThreshold()));
            applySettings(settings::requiredClusterType, computeSettingsValue(ClusterSettings::getRequiredClusterType, defaultSettings.getClusterSettings(), clusterSettings, null));
            applySettings(it -> settings.serverSelectionTimeout(it.longValue(), TimeUnit.MILLISECONDS), computeSettingsValue((ClusterSettings it) -> it.getServerSelectionTimeout(TimeUnit.MILLISECONDS), defaultSettings.getClusterSettings(), clusterSettings, connectionString.getServerSelectionTimeout()));
            applySettings(settings::serverSelector, computeSettingsValue(ClusterSettings::getServerSelector, defaultSettings.getClusterSettings(), clusterSettings, null));
            List<ClusterListener> clusterListeners = computeSettingsValue(ClusterSettings::getClusterListeners, defaultSettings.getClusterSettings(), clusterSettings, null);
            if (clusterListeners != null) {
                clusterListeners.forEach(settings::addClusterListener);
            }
        }).applyToConnectionPoolSettings(settings -> {
            applySettings(it -> settings.maintenanceFrequency(it, TimeUnit.MILLISECONDS), computeSettingsValue((ConnectionPoolSettings it) -> it.getMaintenanceFrequency(TimeUnit.MILLISECONDS), defaultSettings.getConnectionPoolSettings(), connectionPoolSettings, null));
            applySettings(it -> settings.maxConnectionIdleTime(it.longValue(), TimeUnit.MILLISECONDS), computeSettingsValue((ConnectionPoolSettings it) -> it.getMaxConnectionIdleTime(TimeUnit.MILLISECONDS), defaultSettings.getConnectionPoolSettings(), connectionPoolSettings, connectionString.getMaxConnectionIdleTime()));
            applySettings(it -> settings.maxConnectionLifeTime(it.longValue(), TimeUnit.MILLISECONDS), computeSettingsValue((ConnectionPoolSettings it) -> it.getMaxConnectionLifeTime(TimeUnit.MILLISECONDS), defaultSettings.getConnectionPoolSettings(), connectionPoolSettings, connectionString.getMaxConnectionLifeTime()));
            applySettings(it -> settings.maxWaitTime(it.longValue(), TimeUnit.MILLISECONDS), computeSettingsValue((ConnectionPoolSettings it) -> it.getMaxWaitTime(TimeUnit.MILLISECONDS), defaultSettings.getConnectionPoolSettings(), connectionPoolSettings, connectionString.getMaxWaitTime()));
            applySettings(it -> settings.maintenanceInitialDelay(it, TimeUnit.MILLISECONDS), computeSettingsValue((ConnectionPoolSettings it) -> it.getMaintenanceInitialDelay(TimeUnit.MILLISECONDS), defaultSettings.getConnectionPoolSettings(), connectionPoolSettings, null));
            applySettings(settings::minSize, computeSettingsValue(ConnectionPoolSettings::getMinSize, defaultSettings.getConnectionPoolSettings(), connectionPoolSettings, connectionString.getMinConnectionPoolSize()));
            applySettings(settings::maxSize, computeSettingsValue(ConnectionPoolSettings::getMaxSize, defaultSettings.getConnectionPoolSettings(), connectionPoolSettings, connectionString.getMaxConnectionPoolSize()));
        }).applyToSocketSettings(settings -> {
            applySettings(it -> settings.connectTimeout(it, TimeUnit.MILLISECONDS), computeSettingsValue((SocketSettings it) -> it.getConnectTimeout(TimeUnit.MILLISECONDS), defaultSettings.getSocketSettings(), socketSettings, connectionString.getConnectTimeout()));
            applySettings(it -> settings.readTimeout(it, TimeUnit.MILLISECONDS), computeSettingsValue((SocketSettings it) -> it.getReadTimeout(TimeUnit.MILLISECONDS), defaultSettings.getSocketSettings(), socketSettings, connectionString.getSocketTimeout()));
            applySettings(settings::receiveBufferSize, computeSettingsValue(SocketSettings::getReceiveBufferSize, defaultSettings.getSocketSettings(), socketSettings, null));
            applySettings(settings::sendBufferSize, computeSettingsValue(SocketSettings::getSendBufferSize, defaultSettings.getSocketSettings(), socketSettings, null));
        }).applyToServerSettings(settings -> {
            applySettings(it -> settings.minHeartbeatFrequency(it.intValue(), TimeUnit.MILLISECONDS), computeSettingsValue((ServerSettings it) -> it.getMinHeartbeatFrequency(TimeUnit.MILLISECONDS), defaultSettings.getServerSettings(), serverSettings, null));
            applySettings(it -> settings.heartbeatFrequency(it.intValue(), TimeUnit.MILLISECONDS), computeSettingsValue((ServerSettings it) -> it.getHeartbeatFrequency(TimeUnit.MILLISECONDS), defaultSettings.getServerSettings(), serverSettings, connectionString.getHeartbeatFrequency()));
            settings.applySettings(serverSettings);
        }).autoEncryptionSettings(// 
        mongoClientSettings.getAutoEncryptionSettings()).codecRegistry(// 
        mongoClientSettings.getCodecRegistry());
        applySettings(builder::readConcern, computeSettingsValue(defaultSettings.getReadConcern(), mongoClientSettings.getReadConcern(), connectionString.getReadConcern()));
        applySettings(builder::writeConcern, computeSettingsValue(defaultSettings.getWriteConcern(), mongoClientSettings.getWriteConcern(), connectionString.getWriteConcern()));
        applySettings(builder::readPreference, computeSettingsValue(defaultSettings.getReadPreference(), mongoClientSettings.getReadPreference(), connectionString.getReadPreference()));
        applySettings(builder::retryReads, computeSettingsValue(defaultSettings.getRetryReads(), mongoClientSettings.getRetryReads(), connectionString.getRetryReads()));
        applySettings(builder::retryWrites, computeSettingsValue(defaultSettings.getRetryWrites(), mongoClientSettings.getRetryWrites(), connectionString.getRetryWritesValue()));
        applySettings(builder::uuidRepresentation, computeSettingsValue(null, mongoClientSettings.getUuidRepresentation(), UuidRepresentation.JAVA_LEGACY));
    }
    if (!CollectionUtils.isEmpty(credential)) {
        builder = builder.credential(credential.iterator().next());
    }
    if (StringUtils.hasText(replicaSet)) {
        builder.applyToClusterSettings((settings) -> {
            settings.requiredReplicaSetName(replicaSet);
        });
    }
    return builder.build();
}
Also used : ConnectionPoolSettings(com.mongodb.connection.ConnectionPoolSettings) Arrays(java.util.Arrays) DataAccessException(org.springframework.dao.DataAccessException) MongoCredential(com.mongodb.MongoCredential) MongoClient(com.mongodb.client.MongoClient) ClusterSettings(com.mongodb.connection.ClusterSettings) Function(java.util.function.Function) ServerSettings(com.mongodb.connection.ServerSettings) AbstractFactoryBean(org.springframework.beans.factory.config.AbstractFactoryBean) PersistenceExceptionTranslator(org.springframework.dao.support.PersistenceExceptionTranslator) SocketSettings(com.mongodb.connection.SocketSettings) Nullable(org.springframework.lang.Nullable) ServerAddress(com.mongodb.ServerAddress) SslSettings(com.mongodb.connection.SslSettings) ObjectUtils(org.springframework.util.ObjectUtils) MongoClients(com.mongodb.client.MongoClients) ClusterListener(com.mongodb.event.ClusterListener) UuidRepresentation(org.bson.UuidRepresentation) UnknownHostException(java.net.UnknownHostException) Collectors(java.util.stream.Collectors) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) Builder(com.mongodb.MongoClientSettings.Builder) List(java.util.List) ConnectionString(com.mongodb.ConnectionString) CollectionUtils(org.springframework.util.CollectionUtils) MongoClientSettings(com.mongodb.MongoClientSettings) SpringDataMongoDB(org.springframework.data.mongodb.SpringDataMongoDB) StringUtils(org.springframework.util.StringUtils) ClusterSettings(com.mongodb.connection.ClusterSettings) Builder(com.mongodb.MongoClientSettings.Builder) MongoClientSettings(com.mongodb.MongoClientSettings) SocketSettings(com.mongodb.connection.SocketSettings) SslSettings(com.mongodb.connection.SslSettings) ServerSettings(com.mongodb.connection.ServerSettings) ClusterListener(com.mongodb.event.ClusterListener) ConnectionString(com.mongodb.ConnectionString) ConnectionPoolSettings(com.mongodb.connection.ConnectionPoolSettings)

Aggregations

ClusterSettings (com.mongodb.connection.ClusterSettings)24 ServerAddress (com.mongodb.ServerAddress)18 ClusterId (com.mongodb.connection.ClusterId)15 RepeatedTest (org.junit.jupiter.api.RepeatedTest)12 Test (org.junit.jupiter.api.Test)10 FutureResultCallback (com.mongodb.async.FutureResultCallback)6 ServerSelector (com.mongodb.selector.ServerSelector)6 MongoTimeoutException (com.mongodb.MongoTimeoutException)5 ConnectionString (com.mongodb.ConnectionString)4 MongoClientSettings (com.mongodb.async.client.MongoClientSettings)4 ConnectionPoolSettings (com.mongodb.connection.ConnectionPoolSettings)3 ServerSettings (com.mongodb.connection.ServerSettings)3 SocketSettings (com.mongodb.connection.SocketSettings)3 ArrayList (java.util.ArrayList)3 MongoClientException (com.mongodb.MongoClientException)2 MongoConfigurationException (com.mongodb.MongoConfigurationException)2 MongoCredential (com.mongodb.MongoCredential)2 Builder (com.mongodb.async.client.MongoClientSettings.Builder)2 SslSettings (com.mongodb.connection.SslSettings)2 Duration (java.time.Duration)2