您好,登錄后才能下訂單哦!
這篇文章主要介紹“mongodb怎么使用docker搭建replicaSet集群與變更監聽”,在日常操作中,相信很多人在mongodb怎么使用docker搭建replicaSet集群與變更監聽問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”mongodb怎么使用docker搭建replicaSet集群與變更監聽”的疑惑有所幫助!接下來,請跟著小編一起來學習吧!
在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)
在主機1和主機2上安裝好docker,并確保兩臺主機能正常通信
在啟動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
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集群與變更監聽”的學習就結束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學習,快去試試吧!若想繼續學習更多相關知識,請繼續關注億速云網站,小編會繼續努力為大家帶來更多實用的文章!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。