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)

docker方式mongodb集群安装

在主机1和主机2上安装好docker,并确保两台主机能正常通信

目录与key准备

在启动mongodb前,先准备好对应的目录与访问key

  1. #在所有主机都创建用于存储mongodb数据的文件夹
  2. mkdir ~/mongo-data/{data,key,backup}
  3. #设置key文件,用于在集群机器间互相访问,各主机的key需要保持一致
  4. cd ~/mongodata
  5. #在某一节点创建key
  6. openssl rand base64 123 > key/mongors.key
  7. sudo chown 999 key/mongors.key
  8. #不能是755, 权限太大不行.
  9. sudo chmod 600 key/mongors.key
  10. #将key复制到他节点
  11. scp key/mongors.key root@192.168.1.12:/root/mongodata/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”)

再执行以下命令进行初始化

  1. var config={
  2.          _id:“haiyangReplset”,
  3.          members:[
  4.              {_id:0,host:“192.168.1.11:27017”},
  5.              {_id:1,host:“192.168.1.12:27017”},
  6. ]};
  7. rs.initiate(config)

执行成功后,可以看到一个节点为主节点,另一个节点为从节点

-1

其他相关命令

  1. #查看副本集状态
  2. rs.status()
  3. #查看副本集配置
  4. rs.conf()
  5. #添加节点
  6. rs.add( { host: “ip:port”} )
  7. #删除节点
  8. 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

-2

库与监控信息一目了然~

变更监听

对于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功能。

  1. package io.github.puhaiyang;
  2.  
  3. import com.google.common.collect.Lists;
  4. import com.mongodb.client.*;
  5. import org.apache.commons.lang3.StringUtils;
  6. import org.bson.Document;
  7. import org.bson.conversions.Bson;
  8. import org.slf4j.Logger;
  9. import org.slf4j.LoggerFactory;
  10.  
  11. import java.util.ArrayList;
  12. import java.util.Arrays;
  13. import java.util.List;
  14. import java.util.Objects;
  15. import java.util.Optional;
  16. import java.util.Scanner;
  17. import java.util.concurrent.CompletableFuture;
  18.  
  19. /**
  20.      * @author puhaiyang
  21.      * @since 2023/3/30 20:01
  22.      * MongodbWatchTestMain
  23.      */
  24. public class MongodbWatchTestMain {
  25.  
  26.      public static void main(String[] args) throws Exception {
  27.          String uri = “mongodb://admin:123456@192.168.1.11:27017,192.168.1.12:27017/?replicaSet=haiyangReplset”;
  28.          MongoClient mongoClient = MongoClients.create(uri);
  29.          MongoDatabase mongoDatabase = mongoClient.getDatabase(“my-test-db”);
  30.          String myTestCollectionName = “myTestCollection”;
  31.          //获取出collection
  32.          MongoCollection<Document> mongoCollection = initCollection(mongoDatabase, myTestCollectionName);
  33.          //进行watch
  34.          CompletableFuture.runAsync(() -> {
  35.              while (true) {
  36.                  List<Bson> pipeline = Lists.newArrayList(
  37.                      Aggregates.match(Filters.in(“ns.coll”, myTestCollectionName)),
  38.                      Aggregates.match(Filters.in(“operationType”, Arrays.asList(“insert”, “update”, “replace”, “delete”)))
  39.                  );
  40.                  ChangeStreamIterable<Document> changeStream = mongoDatabase.watch(pipeline)
  41.                      .fullDocument(FullDocument.UPDATE_LOOKUP)
  42.                      .fullDocumentBeforeChange(FullDocumentBeforeChange.WHEN_AVAILABLE);
  43.  
  44.                  changeStream.forEach(event -> {
  45.                      String collectionName = Objects.requireNonNull(event.getNamespace()).getCollectionName();
  46.                      System.out.println(“——–> event:” + event.toString());
  47.                  });
  48.              }
  49.          });
  50.  
  51.          //数据变更测试
  52.          {
  53.              Thread.sleep(3_000);
  54.              InsertOneResult insertResult = mongoCollection.insertOne(new Document(“test”, “sample movie document”));
  55.              System.out.println(“Success! Inserted document id: “ + insertResult.getInsertedId());
  56.              UpdateResult updateResult = mongoCollection.updateOne(new Document(“test”, “sample movie document”), Updates.set(“field2”, “sample movie document update”));
  57.              System.out.println(“Updated “ + updateResult.getModifiedCount() + ” document.”);
  58.              DeleteResult deleteResult = mongoCollection.deleteOne(new Document(“field2”, “sample movie document update”));
  59.              System.out.println(“Deleted “ + deleteResult.getDeletedCount() + ” document.”);
  60.          }
  61.  
  62.          new Scanner(System.in).next();
  63.      }
  64.  
  65.      private static MongoCollection<Document> initCollection(MongoDatabase mongoDatabase, String myTestCollectionName) {
  66.          ArrayList<Document> existsCollections = mongoDatabase.listCollections().into(new ArrayList<>());
  67.          Optional<Document> existsCollInfoOpl = existsCollections.stream().filter(doc -> StringUtils.equals(myTestCollectionName, doc.getString(“name”))).findFirst();
  68.          existsCollInfoOpl.ifPresent(collInfo -> {
  69.              //确保开启了changeStreamPreAndPost
  70.              Document changeStreamPreAndPostImagesEnable = collInfo.get(“options”, Document.class).get(“changeStreamPreAndPostImages”, Document.class);
  71.              if (changeStreamPreAndPostImagesEnable != null && !changeStreamPreAndPostImagesEnable.getBoolean(“enabled”)) {
  72.                  Document mod = new Document();
  73.              mod.put(“collMod”, myTestCollectionName);
  74.                  mod.put(“changeStreamPreAndPostImages”, new Document(“enabled”, true));
  75.                  mongoDatabase.runCommand(mod);
  76.              }
  77.          });
  78.          if (!existsCollInfoOpl.isPresent()) {
  79.              CreateCollectionOptions collectionOptions = new CreateCollectionOptions();
  80.              //创建collection时开启ChangeStreamPreAndPostImages
  81.              collectionOptions.changeStreamPreAndPostImagesOptions(new ChangeStreamPreAndPostImagesOptions(true));
  82.              mongoDatabase.createCollection(myTestCollectionName, collectionOptions);
  83.          }
  84.          return mongoDatabase.getCollection(myTestCollectionName);
  85.      }
  86. }
  87.  
  88.  

输出结果如下:

——–> 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集群内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

标签

发表评论