首頁 > 軟體

mongodb使用docker搭建replicaSet叢集與變更監聽(最新推薦)

2023-04-02 06:02:47

在mongodb如果需要啟用變更監聽功能(watch),mongodb需要在replicaSet或者cluster方式下執行。

replicaSet和cluster從部署難度相比,replicaSet要簡單許多。如果所儲存的資料量規模不算太大的情況下,那麼使用replicaSet方式部署mongodb是一個不錯的選擇。

安裝環境

mongodb版本:mongodb-6.0.5

兩臺主機:主機1(192.168.1.11)、主機2(192.168.1.12)

docker方式mongodb叢集安裝

在主機1和主機2上安裝好docker,並確保兩臺主機能正常通訊

目錄與key準備

在啟動mongodb前,先準備好對應的目錄與存取key

#在所有主機都建立用於儲存mongodb資料的資料夾
mkdir -p ~/mongo-data/{data,key,backup}
#設定key檔案,用於在叢集機器間互相存取,各主機的key需要保持一致
cd ~/mongo-data
#在某一節點建立key
openssl rand -base64 123 > key/mongo-rs.key
sudo chown 999 key/mongo-rs.key
#不能是755, 許可權太大不行. 
sudo chmod 600 key/mongo-rs.key
#將key複製到他節點
scp key/mongo-rs.key root@192.168.1.12:/root/mongo-data/key

以上操作在各主機中建立了 ~/mongo-data/{data,key,backup} 這3個目錄,且mongo-rs.key的內容一致。

執行mongodb

執行下列命令,啟動mongodb

sudo docker run --name mongo --network=host -p 27017:27017 -v ~/mongo-data/data:/data/db -v ~/mongo-data/backup:/data/backup -v ~/mongo-data/key:/data/key -v /etc/localtime:/etc/localtime -e MONGO_INITDB_ROOT_USERNAME=admin -e MONGO_INITDB_ROOT_PASSWORD=123456 -d mongo:6.0.5 --replSet haiyangReplset --auth --keyFile /data/key/mongo-rs.key --bind_ip_all

上面主要將27017埠對映到主機中,並設了admin的預設密碼為123456。
–replSet為指定開啟replicaSet,後面跟的為副本集的名稱。

設定節點

進入某一節點,進行叢集設定

sudo docker exec -it mongo bash
mongosh

初始化叢集前先登入驗證超級管理員admin

use admin
db.auth(“admin”,“123456”)

再執行以下命令進行初始化

var config={
     _id:"haiyangReplset",
     members:[
         {_id:0,host:"192.168.1.11:27017"},
         {_id:1,host:"192.168.1.12:27017"},
]};
rs.initiate(config)

執行成功後,可以看到一個節點為主節點,另一個節點為從節點

其他相關命令

#檢視副本集狀態
rs.status()
#檢視副本集設定
rs.conf()
#新增節點
rs.add( { host: "ip:port"} )
#刪除節點
rs.remove('ip:port')

官方使用者端驗證

在mongodb安裝好後,再用使用者端連線驗證一下。
官方mongodb的使用者端下載地址為:https://www.mongodb.com/try/download/compass

下載完畢後,在使用者端中新建連線。
在本例中,則mongodb的連線地址為:

mongodb://admin:123456@192.168.1.11:27017,192.168.1.12:27017/?authMechanism=DEFAULT&authSource=admin&replicaSet=haiyangReplset

庫與監控資訊一目瞭然~

變更監聽

對於mongodb操作的api在mongodb的官網有比較完備的檔案,java的檔案連線為:https://www.mongodb.com/docs/drivers/java/sync/v4.9/

這裡試一下mongodb中一個比較強悍的功能,記錄的變更監聽。
用這項功能來做一些審計的場景則會非常方便。

官方連結為:https://www.mongodb.com/docs/drivers/java/sync/v4.9/usage-examples/watch/

這裡以java使用者端為例寫個小demo,試一下對於mongodb中集合的建立及watch功能。

package io.github.puhaiyang;

import com.google.common.collect.Lists;
import com.mongodb.client.*;
import org.apache.commons.lang3.StringUtils;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Scanner;
import java.util.concurrent.CompletableFuture;

/**
 * @author puhaiyang
 * @since 2023/3/30 20:01
 * MongodbWatchTestMain
 */
public class MongodbWatchTestMain {

    public static void main(String[] args) throws Exception {
        String uri = "mongodb://admin:123456@192.168.1.11:27017,192.168.1.12:27017/?replicaSet=haiyangReplset";
        MongoClient mongoClient = MongoClients.create(uri);
        MongoDatabase mongoDatabase = mongoClient.getDatabase("my-test-db");
        String myTestCollectionName = "myTestCollection";
        //獲取出collection
        MongoCollection<Document> mongoCollection = initCollection(mongoDatabase, myTestCollectionName);
        //進行watch
        CompletableFuture.runAsync(() -> {
            while (true) {
                List<Bson> pipeline = Lists.newArrayList(
                        Aggregates.match(Filters.in("ns.coll", myTestCollectionName)),
                        Aggregates.match(Filters.in("operationType", Arrays.asList("insert", "update", "replace", "delete")))
                );
                ChangeStreamIterable<Document> changeStream = mongoDatabase.watch(pipeline)
                        .fullDocument(FullDocument.UPDATE_LOOKUP)
                        .fullDocumentBeforeChange(FullDocumentBeforeChange.WHEN_AVAILABLE);

                changeStream.forEach(event -> {
                    String collectionName = Objects.requireNonNull(event.getNamespace()).getCollectionName();
                    System.out.println("--------> event:" + event.toString());
                });
            }
        });

        //資料變更測試
        {
            Thread.sleep(3_000);
            InsertOneResult insertResult = mongoCollection.insertOne(new Document("test", "sample movie document"));
            System.out.println("Success! Inserted document id: " + insertResult.getInsertedId());
            UpdateResult updateResult = mongoCollection.updateOne(new Document("test", "sample movie document"), Updates.set("field2", "sample movie document update"));
            System.out.println("Updated " + updateResult.getModifiedCount() + " document.");
            DeleteResult deleteResult = mongoCollection.deleteOne(new Document("field2", "sample movie document update"));
            System.out.println("Deleted " + deleteResult.getDeletedCount() + " document.");
        }

        new Scanner(System.in).next();
    }

    private static MongoCollection<Document> initCollection(MongoDatabase mongoDatabase, String myTestCollectionName) {
        ArrayList<Document> existsCollections = mongoDatabase.listCollections().into(new ArrayList<>());
        Optional<Document> existsCollInfoOpl = existsCollections.stream().filter(doc -> StringUtils.equals(myTestCollectionName, doc.getString("name"))).findFirst();
        existsCollInfoOpl.ifPresent(collInfo -> {
            //確保開啟了changeStreamPreAndPost
            Document changeStreamPreAndPostImagesEnable = collInfo.get("options", Document.class).get("changeStreamPreAndPostImages", Document.class);
            if (changeStreamPreAndPostImagesEnable != null && !changeStreamPreAndPostImagesEnable.getBoolean("enabled")) {
                Document mod = new Document();
                mod.put("collMod", myTestCollectionName);
                mod.put("changeStreamPreAndPostImages", new Document("enabled", true));
                mongoDatabase.runCommand(mod);
            }
        });
        if (!existsCollInfoOpl.isPresent()) {
            CreateCollectionOptions collectionOptions = new CreateCollectionOptions();
            //建立collection時開啟ChangeStreamPreAndPostImages
            collectionOptions.changeStreamPreAndPostImagesOptions(new ChangeStreamPreAndPostImagesOptions(true));
            mongoDatabase.createCollection(myTestCollectionName, collectionOptions);
        }
        return mongoDatabase.getCollection(myTestCollectionName);
    }
}


輸出結果如下:

--------> event:ChangeStreamDocument{ operationType=insert, resumeToken={"_data": "8264255A0F000000022B022C0100296E5A10046A3E3757D6A64DF59E6D94DC56A9210446645F6964006464255A105A91F005CFB2E6D20004"}, namespace=my-test-db.myTestCollection, destinationNamespace=null, fullDocument=Document{{_id=64255a105a91f005cfb2e6d2, test=sample movie document}}, fullDocumentBeforeChange=null, documentKey={"_id": {"$oid": "64255a105a91f005cfb2e6d2"}}, clusterTime=Timestamp{value=7216272998402097154, seconds=1680169487, inc=2}, updateDescription=null, txnNumber=null, lsid=null, wallTime=BsonDateTime{value=1680169487686}}
Success! Inserted document id: BsonObjectId{value=64255a105a91f005cfb2e6d2}
Updated 1 document.
--------> event:ChangeStreamDocument{ operationType=update, resumeToken={"_data": "8264255A0F000000032B022C0100296E5A10046A3E3757D6A64DF59E6D94DC56A9210446645F6964006464255A105A91F005CFB2E6D20004"}, namespace=my-test-db.myTestCollection, destinationNamespace=null, fullDocument=Document{{_id=64255a105a91f005cfb2e6d2, test=sample movie document, field2=sample movie document update}}, fullDocumentBeforeChange=Document{{_id=64255a105a91f005cfb2e6d2, test=sample movie document}}, documentKey={"_id": {"$oid": "64255a105a91f005cfb2e6d2"}}, clusterTime=Timestamp{value=7216272998402097155, seconds=1680169487, inc=3}, updateDescription=UpdateDescription{removedFields=[], updatedFields={"field2": "sample movie document update"}, truncatedArrays=[], disambiguatedPaths=null}, txnNumber=null, lsid=null, wallTime=BsonDateTime{value=1680169487708}}
--------> event:ChangeStreamDocument{ operationType=delete, resumeToken={"_data": "8264255A0F000000042B022C0100296E5A10046A3E3757D6A64DF59E6D94DC56A9210446645F6964006464255A105A91F005CFB2E6D20004"}, namespace=my-test-db.myTestCollection, destinationNamespace=null, fullDocument=null, fullDocumentBeforeChange=Document{{_id=64255a105a91f005cfb2e6d2, test=sample movie document, field2=sample movie document update}}, documentKey={"_id": {"$oid": "64255a105a91f005cfb2e6d2"}}, clusterTime=Timestamp{value=7216272998402097156, seconds=1680169487, inc=4}, updateDescription=null, txnNumber=null, lsid=null, wallTime=BsonDateTime{value=1680169487721}}
Deleted 1 document.

到此這篇關於mongodb使用docker搭建replicaSet叢集與變更監聽的文章就介紹到這了,更多相關mongodb搭建replicaSet叢集內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com