通过mongo-java-driver Java API设置Mongodb连接池选项

时间:2018-11-09 08:19:14

标签: java mongodb morphia mongo-java-driver

使用Morphia和mongo-java-driver,我正在连接到mongo服务器:

MongoClientOptions.Builder builder = MongoClientOptions.builder();
        builder.sslEnabled(true);
        builder.sslInvalidHostNameAllowed(true);
        builder.maxConnectionIdleTime(0);
        MongoClientOptions sslOptions = builder.build();

        MongoClient mongoClient = new MongoClient(serverAddressList, Arrays.asList(mongoCredential), sslOptions);

其中serverAddressList是 host:port 列表,使用kerberos auth的mongoCredential创建为:

MongoCredential mongoCredential = MongoCredential.createGSSAPICredential("user@REALM.COM");

我想使用以下方法设置自定义连接池参数:

  1. maxPoolSize
  2. minPoolSize
  3. maxIdleTimeMS等

为此,我找到了 ConnectionPoolSettings.Builder com.mongodb.connection.ConnectionPoolSettings 类。

我搜索了示例代码here

ConnectionPoolSettings connectionPoolSettings = ConnectionPoolSettings
                .builder()
                .minSize(MIN_MONGO_POOL_SIZE)
                .maxSize(MONGO_POOL_SIZE)
                .build();
        MongoClientSettings settings = MongoClientSettings
                .builder()
                .readPreference(MONGO_READ_PREFERENCE)
                .credentialList(credentialsList).clusterSettings(clusterSettings)
                .connectionPoolSettings(connectionPoolSettings).build();

有人可以建议使用这些设置来获取MongoClient实例的方法吗?

正在使用的库:

dependencies {
    compile 'org.mongodb:mongodb-driver-sync:3.4.3'
  }

1 个答案:

答案 0 :(得分:1)

最后弄清楚了设置连接池参数的正确方法,所以在这里回答我自己的问题。

我浏览了MongoClientOptions here的源代码 其中connectionPool参数的设置如下:

connectionPoolSettings = ConnectionPoolSettings
                    .builder()
                    .minSize(getMinConnectionsPerHost())
                    .maxSize(getConnectionsPerHost())
                    .maxWaitQueueSize(getThreadsAllowedToBlockForConnectionMultiplier()
                    * getConnectionsPerHost())
                    .maxWaitTime(getMaxWaitTime(), MILLISECONDS)
                    .maxConnectionIdleTime(getMaxConnectionIdleTime(), MILLISECONDS)
                    .maxConnectionLifeTime(getMaxConnectionLifeTime(), MILLISECONDS)
                    .build();

我们可以看到minSize和maxSize值是从getMinConnectionsPerHost();getConnectionsPerHost();方法中获取的。因此,要更改和自定义客户端代码中的连接池参数,我们只需将maxConnectionIdleTime和minConnectionsPerHost值添加到构建器中,如下所示:

MongoClientOptions.Builder builder = MongoClientOptions.builder();
    builder.maxConnectionIdleTime(0);
    builder.minConnectionsPerHost(50);
    builder.connectionsPerHost(200);
    MongoClientOptions sslOptions = builder.build();

此代码成功打开了与mongodb服务器主机的最少指定连接。

LOG : 00:20:00,714 INFO  [org.mongodb.driver.connection] (pool-1-thread-1) Opened connection [connectionId{localValue:50}] to server.com:27180