目标
在3.8版本中,设置客户端连接超时时间
版本
在项目中引用的3.8版本,引用的版本如下
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.8.1</version>
</dependency>
官方文档中的做法
首先在官方文档的教程中,找到关于超时时间的设置如下
String user; // the user name
String database; // the name of the database in which the user is defined
char[] password; // the password as a character array
// ...
MongoCredential credential = MongoCredential.createCredential(user, database, password);
MongoClientOptions.Builder options = MongoClientOptions.builder()
.socketTimeout(1000)
.maxWaitTime(1000)
.connectTimeout(1000)
.serverSelectionTimeout(1000);
MongoClient mongoClient = new MongoClient(new ServerAddress("host1", 27017),
Arrays.asList(credential),
options);
但是按照上面的写法做的时候,发送在3.8版本里,new MongoClient这种方法在程序中已经被废弃,不鼓励使用,应该是官方文档还没有来得及更新,于是开始探索该版程序中,超时时间如何设置。
采用作法
经过查询API,找到了出了上面方法之外的另一中可行的方法
mongoClient = MongoClients.create(
MongoClientSettings.builder()
.applyToClusterSettings(builder ->
builder.hosts(Arrays.asList(new ServerAddress(config.getMongoUrl(), config.getMongoPort())))
.serverSelectionTimeout(10,TimeUnit.SECONDS))
.credential(credential)
.build());
这个方法中,仅仅设置了serverSelectTimeout的时间,没有找到上面的其他超时时间的设置,还在学习中,如果后面找到了,再补全...
网友评论