先運行mongodb確定是必須的,而後導入如下包:html
import com.mongodb.MongoClient; import com.mongodb.MongoClientURI; import com.mongodb.ServerAddress; import com.mongodb.MongoCredential; import com.mongodb.MongoClientOptions;
MongoClient
MongoClient()實例表示到數據庫的鏈接池; 你將只須要MongoClient類的一個實例,即便有多個線程也是同樣。java
重要:git
一般,您只能爲給定的MongoDB部署(例如獨立,副本集或分片羣集)建立一個MongoClient實例,並在您的應用程序中使用它。 可是,若是您建立了多個實例:github
如下幾種方法:mongodb
1.數據庫
MongoClient mongoClient = new MongoClient( "host1" , 27017 );
2. You can specify the MongoClientURI
connection string.函數
MongoClient mongoClient = new MongoClient(new MongoClientURI("mongodb://host1:27017"));
MongoDB將自動發現主要和副本。post
You can specify the members using the MongoClientURI
connection string:ui
指定兩個副本集:url
MongoClient mongoClient = new MongoClient( new MongoClientURI("mongodb://host1:27017,host2:27017,host3:27017"));
至少有一個副本集和副本集選項的成員:
MongoClient mongoClient = new MongoClient( new MongoClientURI( "mongodb://host1:27017,host2:27017,host3:27017/?replicaSet=myReplicaSet"));
你可使用ServerAddress指定副本集中的全部成員.
MongoClient mongoClient = new MongoClient( Arrays.asList(new ServerAddress("host1", 27017), new ServerAddress("host2", 27017), new ServerAddress("host3", 27017)));
要鏈接到分片羣集,請將mongos實例或多個實例指定給MongoClient構造函數。
鏈接到一個mongos實例:
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
鏈接多個 mongos
實例:
MongoClient mongoClient = new MongoClient( new MongoClientURI("mongodb://host1:27017,host2:27017"));
MongoClient mongoClient = new MongoClient( Arrays.asList(new ServerAddress("host1", 27017), new ServerAddress("host2", 27017)));
您可使用MongoClientURI
或MongoClientOptions
或二者來指定鏈接設置。
例如,您能夠在MongoClientURI
鏈接字符串中指定 TLS/SSL
和身份驗證設置:
MongoClientURI uri = new MongoClientURI("mongodb://user1:pwd1@host1/?authSource=db1&ssl=true"); MongoClient mongoClient = new MongoClient(uri);
您還可使用MongoClientOptions
來指定 TLS/SSL
和MongoCredential
的認證信息:
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 options = MongoClientOptions.builder().sslEnabled(true).build(); MongoClient mongoClient = new MongoClient(new ServerAddress("host1", 27017), Arrays.asList(credential), options);
這裏只是官方給的簡單演示鏈接, 不可直接用於生產環境, 好比: 這裏邊沒有配置讀寫關注, 讀取偏好, 鏈接池配置等都是默認的. 而這些默認值直接用於生產環境確定是不行的.
至於生產環境怎麼配置, 要根據業務狀況來實際分析, 我在後邊會提供一個參考.
參考官方文檔:
https://mongodb.github.io/mongo-java-driver/3.4/driver/tutorials/connect-to-mongodb/