Java连接MongoDB报错“java.lang.IllegalArgumentException: clusterListener can not be null”的解决办法
我使用的MongoDB版本是3.6.9。
下面是一个很基础的示例代码,功能就是连接MongoDB:
package com.zifeiy.snowflake.handle.etl.mongodb;
import com.mongodb.MongoClient;
public class MongodbTest {
public static void main(String[] args) {
MongoClient mongoClient = new MongoClient();
}
}
但是执行后报错:
Exception in thread "main" java.lang.IllegalArgumentException: clusterListener can not be null
at com.mongodb.assertions.Assertions.notNull(Assertions.java:37)
at com.mongodb.connection.ClusterSettings$Builder.addClusterListener(ClusterSettings.java:218)
at com.mongodb.connection.DefaultClusterFactory.getClusterSettings(DefaultClusterFactory.java:190)
at com.mongodb.connection.DefaultClusterFactory.create(DefaultClusterFactory.java:117)
at com.mongodb.Mongo.createCluster(Mongo.java:744)
at com.mongodb.Mongo.createCluster(Mongo.java:728)
at com.mongodb.Mongo.<init>(Mongo.java:293)
at com.mongodb.Mongo.<init>(Mongo.java:288)
at com.mongodb.Mongo.<init>(Mongo.java:284)
at com.mongodb.MongoClient.<init>(MongoClient.java:179)
at com.mongodb.MongoClient.<init>(MongoClient.java:156)
at com.mongodb.MongoClient.<init>(MongoClient.java:117)
at com.zifeiy.snowflake.handle.etl.mongodb.MongodbTest.main(MongodbTest.java:7)
解决办法是:将pom.xml中的mongodb-driver版本改成3.6的就可以了:
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver</artifactId>
<version>3.6.4</version>
</dependency>
改成3.6之后再次运行出现如下提示,说明连接成功:
07:38:15.249 [main] INFO org.mongodb.driver.cluster - Cluster created with settings {hosts=[127.0.0.1:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
07:38:15.276 [main] DEBUG org.mongodb.driver.cluster - Updating cluster description to {type=UNKNOWN, servers=[{address=127.0.0.1:27017, type=UNKNOWN, state=CONNECTING}]