1. 程式人生 > >基於最新mongodb-driver3.7,Java連接MongoDB

基於最新mongodb-driver3.7,Java連接MongoDB

成功 HR mongod 配置 serve tps conn 等待 client

寫在前面:我現在在頭條寫博客文章。大家可以關註下我的頭條號:我是樂樂樂樂呀

目前最新的MongoDB連接版本為3.8,不過還是測試版本的。可以說截止目前為止,3.7是最新的版本。

在3.7版本中,以前舊版本有些方法已經申明為過期方法了:如,getDB()方法

技術分享圖片

這涉及到的一系列CRUD方法都發生了變化。

下面貼上一段基於3.7版本的連接代碼:

public static void main(String[] args) {

MongoClientOptions.Builder builder = MongoClientOptions.builder();

//最大連接數

builder.connectionsPerHost(10);

//最小連接數

builder.minConnectionsPerHost(5);

//超時時間

builder.connectTimeout(1000*3);

// 一個線程成功獲取到一個可用數據庫之前的最大等待時間

builder.maxWaitTime(5000);

//此參數跟connectionsPerHost的乘機為一個線程變為可用的最大阻塞數,超過此乘機數之後的所有線程將及時獲取一個異常.eg.connectionsPerHost=10 and threadsAllowedToBlockForConnectionMultiplier=5,最多50個線程等級一個鏈接,推薦配置為5

builder.threadsAllowedToBlockForConnectionMultiplier(5);

//最大空閑時間

builder.maxConnectionIdleTime(1000*10);

//設置池連接的最大生命時間。

builder.maxConnectionLifeTime(1000*10);

//連接超時時間

builder.socketTimeout(1000*10);

MongoClientOptions myOptions = builder.build();

List<ServerAddress> serverAddressList = new ArrayList<>();

ServerAddress record = new ServerAddress("127.0.0.1");

serverAddressList.add(record);

MongoCredential credential = MongoCredential.createCredential("loger","db_test","apple".toCharArray());

MongoClient mongoClient = new MongoClient(serverAddressList, credential, myOptions);

MongoDatabase dbTest = mongoClient.getDatabase("db_test");

String name = dbTest.getName();

System.out.println("數據庫名字:"+name);

MongoIterable<String> strings = dbTest.listCollectionNames();

for(String str:strings){

System.out.println("數據庫表名:"+str);

}

}

截圖版:

技術分享圖片

代碼中都有註釋,這裏就不多說了。執行看下結果:

技術分享圖片

MongoDB連接成功!

說明:每一個數據庫,建議單獨設置一個賬戶,用超級管理員賬戶在java client下操作其他數據庫,似乎有問題。。。

基於最新mongodb-driver3.7,Java連接MongoDB