MongoDB叢集搭建與java程式碼操作MongoDB示例
MongoDB叢集搭建與java程式碼操作MongoDB示例
MongoDB叢集搭建過程
1. MongoDB Replica set叢集搭建準備(主從仲裁)
- 介質(根據作業系統下載相應版本):https://www.mongodb.com/download-center/v2/community
- 叢集配置手冊(官方):https://docs.mongodb.com/manual/reference/configuration-options/
2. 叢集搭建(1主,1從,1仲裁)
- 根據作業系統解壓相應的安裝包
- 準備目錄
mkdir ~/primary //存放主節點目錄
mkdir ~/secondary //存放從節點目錄
mkdir ~/arbiter //存放仲裁者節點目錄
mkdir ~/primary/data //存放主節點資料目錄
mkdir ~/primary/keyFile //存放節點間鑑權檔案目錄
mkdir ~/primary/log //存放主節點日誌檔案目錄
mkdir ~/primary/pid //存放主節點pid檔案目錄
vi ~/primary/log/mongo.log //儲存主節點日誌的檔案
vi ~/primary/pid/mongo.pid //儲存主節點pid的檔案
vi ~/primary/keyFile/key.key //儲存節點間認證祕鑰的檔案
vi ~/primary/mongo.conf //儲存主節點配置資訊的檔案
注: 4-11步驟需要在 /secondary和~/arbiter建立相同的目錄檔案
3. 配置內部認證祕鑰
在所有角色的keyFile目錄下的key.key的檔案中寫入相同的祕鑰, 該檔案需要設定600許可權, 該檔案在所有節點下應保證完全一致
4. 配置啟動配置資訊
vim ~/primary/mongo.conf
vim ~/secondary /mongo.conf
vim ~/arbiter /mongo.conf
以上三個檔案中配置以下資訊
security:
authorization: enabled #開啟驗證
keyFile: "E:/tools/mongoDB-win/mongodb-win32-x86_64-2008plus-ssl-4.0.3/primary/keyFile/key.txt" #指定祕鑰檔案
storage:
dbPath: "E:/tools/mongoDB-win/mongodb-win32-x86_64-2008plus-ssl-4.0.3/primary/data" #指定儲存目錄
directoryPerDB: true #開啟按庫分目錄
systemLog:
destination: file
path: "E:/tools/mongoDB-win/mongodb-win32-x86_64-2008plus-ssl-4.0.3/primary/log/mongo.log" #指定log檔案
logAppend: true #追加的方式記錄日誌
processManagement:
pidFilePath: "E:/tools/mongoDB-win/mongodb-win32-x86_64-2008plus-ssl-4.0.3/primary/pid/mongo.pid" #指定pid檔案
replication:
replSetName: "testdb" #指定叢集名稱
oplogSizeMB: 100 #指定日誌大小
net:
bindIp: 0.0.0.0 #指定允許訪問的ip, 如果想要允許所有ip可訪問, 此項要配置成0.0.0.0, 如果不配則預設只可以被127.0.0.1訪問
port: 8081 #指定埠
5. 配置叢集
-
遮蔽認證(註釋掉security的配置)啟動叢集(mongod -f ~/primary/mongo.conf )
-
連線客戶端(mongo --port=port),進入mongo shell端
-
配置節點角色
-
在mongo shell中執行:
cfg={ _id:"testdb", members:[ {_id:0,host:'127.0.0.1:8081',priority:2}, {_id:1,host:'127.0.0.1:8082',priority:1}, {_id:2,host:'127.0.0.1:8083',arbiterOnly:true}] };
注:_id:“testdb”,要與配置檔案中的replSetName一致,priority高的將成為主節點,arbiterOnly:true節點將成為仲裁者節點
-
-
rs.initiate(cfg);啟用配置
6. 設定使用者
-
連線主節點,進入mongo shell端
-
建立使用者
db.createUser({user:"yourAccount", pwd:"yourPassword",roles:[{role:"userAdminAnyDatabases", db:"admin"}]})
注:role:“userAdminAnyDatabases”,角色需要配置mongoDB中已經存在的角色,db:"admin"角色所屬資料庫(角色是隨資料庫走的)
注:叢集模式必須在主節點建立角色, 主節點建立的角色將被同步到叢集各節點
7. 放開認證遮蔽,重啟叢集
java使用MongoDB叢集Demo
1. maven依賴
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.8.0</version>
</dependency>
2. 配置檔案
#使用者名稱
userName=mongo
#密碼
pwd=mongo
#資料庫名
adminDb=test
#資料庫名
dbname=test
#叢集host個數(除仲裁節點)
len=2
#host地址
host1=192.168.8.1:27017
host2=192.168.8.2:27017
#每臺主機最大連線數
connectionsPerHost=50
#執行緒佇列數
threads=10
#是否需要身份驗證 1要 0不要
authentication=1
#最大等待時間
maxWaitTime=300000
#socket超時時間
socketTimeout=100000
#連線超時時間
connectTimeout=25000
3. java 程式碼
public class MongoDBUtil {
private static MongoClient mg;
private static MongoDatabase mongoDatabase;
static{
ResourceBundle mongoProperties = ResourceBundle.getBundle("mongo"); // 配置檔案
String connectionsPerHost = mongoProperties.getString("connectionsPerHost"); // 連線池數量
String maxWaitTime = mongoProperties.getString("maxWaitTime"); // 最大等待時間
String socketTimeout = mongoProperties.getString("socketTimeout"); // scoket超時時間
String connectTimeout = mongoProperties.getString("connectTimeout"); // 連線超時時間
MongoClientOptions options = MongoClientOptions.builder()
.connectionsPerHost(Integer.parseInt(connectionsPerHost))
.maxWaitTime(Integer.parseInt(maxWaitTime))
.socketTimeout(Integer.parseInt(socketTimeout))
.connectTimeout(Integer.parseInt(connectTimeout)).build();
String hostLen = mongoProperties.getString("len");
List<ServerAddress> hosts = new ArrayList<ServerAddress>(); // 所有主機
for (int i = 1; i <= Integer.parseInt(hostLen); i++) {
String host = mongoProperties.getString("host" + i);
hosts.add(new ServerAddress(host));
System.out.println("host是:::"+host);
}
List<MongoCredential> credentials = new ArrayList<MongoCredential>();
if (mongoProperties.getString("authentication").equals("1")) {
MongoCredential credential = MongoCredential.createCredential(
mongoProperties.getString("userName"), mongoProperties
.getString("adminDb"),
mongoProperties.getString("pwd").toCharArray()); // 需要驗證
credentials.add(credential);
}
mg = new MongoClient(hosts, credentials, options);
mongoDatabase = mg.getDatabase(mongoProperties.getString("dbname"));
}
public static MongoDatabase getMongoDatabase() {
return mongoDatabase;
}
public static void setMongoDatabase(MongoDatabase mongoDatabase) {
MongoDBUtil.mongoDatabase = mongoDatabase;
}
/**
* 插入文件資料
* @param mongoCollection
* @param params
*/
public static boolean insertDoucument(final MongoCollection<Document> mongoCollection, Document document){
boolean result =false;
if(null == mongoCollection) {
return false;
}
try {
mongoCollection.insertOne(document);
result =true;
}catch (Exception e){
e.printStackTrace();
}
return result;
}
/**
* 根據欄位精確查詢
* @param
*/
public static FindIterable<Document> selectDocument(@SuppressWarnings("rawtypes") MongoCollection mongoCollection, String filed, String value){
if(mongoCollection == null ){
return null;
}
@SuppressWarnings("unchecked")
FindIterable<Document> documents = mongoCollection.find(new Document(filed,value));
return documents;
}
/**
*
* Copyright(c) 2018, fapiao.gov.cn. All rights reserved .
* Author: liuyang
* Created: 2018年10月19日
* Description
* 刪除document
*/
public static boolean deleteDocument(MongoCollection mongoCollection, String filed, String value){
boolean result =false;
try{
DeleteResult dd=mongoCollection.deleteOne(new Document(filed,value));
int count = (int) dd.getDeletedCount();
if(count==1){
result=true;
}
}catch(Exception e){
System.out.println("mongoDb刪除失敗");
}
return result;
}
}
public class TestMongoDB {
static MongoDatabase mongoDatabase = MongoDBUtil.getMongoDatabase();
public static void main(String[] args) {
delete();
}
public static void add() {
System.out.println("dddddddddddddd");
MongoCollection<Document> collection = mongoDatabase.getCollection("test");
Document document = new Document();
document.append("rowKey", "a93da192-0d89-4823-b8cb-e791679209qw-1540453023072");
document.append("pic", 111111111);
MongoDBUtil.insertDoucument(collection, document);
}
public static void get() {
System.out.println("ggggggggggggg");
MongoCollection<Document> collection = mongoDatabase.getCollection("test");
Document documentMessage = new Document("rowKey", "a93da192-0d89-4823-b8cb-e791679209qw-1540453023072");
FindIterable<Document> documents = collection.find(documentMessage);
for (Document documentT : documents) {
Integer picCode = (Integer) documentT.get("pic");
System.out.println(picCode);
}
}
public static void delete() {
System.out.println("ddddddddddddd");
MongoCollection<Document> collection = mongoDatabase.getCollection("test");
MongoDBUtil.deleteDocument(collection, "rowKey", "a93da192-0d89-4823-b8cb-e791679209qw-1540453023072");
}
}