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)

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)

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

mongodb使用docker搭建replicaSet集群与变更监听

其他相关命令

#查看副本集状态
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使用docker搭建replicaSet集群与变更监听

库与监控信息一目了然~

变更监听

对于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);
    }
}

输出结果如下:文章来源地址https://www.toymoban.com/news/detail-431932.html

--------> 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集群与变更监听的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 使用Docker搭建开发环境:MySQL、Redis、MongoDB和Selenium Grid

    Docker 是一个开源的应用容器引擎,让开发者可以打包他们的应用以及依赖包到一个可移植的容器中,然后发布到任何支持Docker的平台上。在本篇博客中,我们将详细介绍如何用Docker安装MySQL、Redis、MongoDB和Selenium Grid,并给出相应的代码案例。 在开始之前,确保您的系统上安

    2024年02月19日
    浏览(32)
  • MongoDB分片集群搭建

    MongoDB 有三种集群架构模式,分别为主从复制(Master-Slaver)、副本集(Replica Set)和分片(Sharding)模式。 Master-Slaver 是一种主从复制的模式,目前已经不推荐使用 ReplicaSet模式取代了Master-Slaver模式,是一种互为主从的关系。Replica Set 将数据复制多份保存,不同服务器保存同一

    2024年01月19日
    浏览(35)
  • mongodb集群搭建

    下载mongodb-linux-x86_64-rhel70-5.0.18 vi mongodb.conf 导入环境变量中 以上操作在每个机器都做一遍 之后选择一个作为主节点,启动mongodb 启动: mongod -f ../conf/mongodb.conf --replSet \\\"grap\\\" 每个机器都做一边,最后连接一台机器 Mongo进去数据库中,(注意一定不要先执行rs.initiate(),否则后

    2024年02月16日
    浏览(31)
  • 如何在Ubuntu系统使用Docker搭建MongoDB结合内网穿透实现公网连接

    本文主要介绍如何在Linux Ubuntu系统使用Docker快速部署MongoDB,并结合cpolar内网穿透工具实现公网远程访问本地数据库。 MongoDB服务端可以运行在Linux、Windows、MacOS平台,可以存储比较复杂的数据类型,支持的查询语言非常强大,几乎可以实现类似关系数据库单表查询的绝大部分

    2024年03月26日
    浏览(48)
  • 使用docker搭建hadoop集群

    必应壁纸供图 (img-CBr9VbGk-1687962511910)]

    2024年02月11日
    浏览(32)
  • 使用docker搭建mysql集群

    1、架构图 2、解说 mysql_1 、 mysql_2 、 mysql_3 是一组主从模式,同理 mysql_4 、 mysql_5 、 mysql_6 也是一组主从模式 从上面的图可以看出 mysql_1 和 mysql_4 是主节点,可以进行增删改查操作,但是子几点只能查询操作 如果 mysql_1 节点出现问题了,有 mysql_4 节点组正常工作 1、使用镜像创建

    2024年02月12日
    浏览(47)
  • 使用docker搭建RocketMQ(非集群搭建官方镜像)

    之前在使用 RocketMQ 官方的包在搭建的时候,发现好多问题,什么修改内存大小,然后启动 broker 报错,类似 service not available now, maybe disk full 等等… 最后决定还是重新用 docker 搭建下,感觉这样子玩坏了,可以直接把容器干掉,重新启动一个新的容器,毕竟是在学习阶段,这

    2024年02月13日
    浏览(40)
  • 使用Docker搭建Redis主从集群

    欢迎来到 请回答1024 的博客 🍓🍓🍓欢迎来到 请回答1024的博客 关于博主 : 我是 请回答1024 ,一个追求数学与计算的边界、时间与空间的平衡,0与1的延伸的后端开发者。 博客特色 : 在我的博客中,开设了如下专栏( 点击可以进入专栏奥~ ): Java、MySQL、Redis、Spring、SpringB

    2024年04月24日
    浏览(33)
  • 如何使用Docker搭建ZooKeepe集群

    1、拉取镜像 2、创建网络 Docker创建容器时默认采用bridge网络,自行分配ip,不允许自己指定。在实际部署中,需要指定容器ip,不允许其自行分配ip,尤其在搭建集群时。可以通过docker network create指令创建自己的bridge网络 ,在创建容器时指定网络和ip即可。 3、配置文件 a、创

    2024年02月11日
    浏览(36)
  • Mongodb Replica Sets 副本集群搭建

    Replica Sets 复制集搭建 MongoDB 有三种集群架构模式,分别为主从复制(Master-Slaver)、副本集(Replica Set)和分片(Sharding)模式。 Master-Slaver 是一种主从复制的模式,目前已经不推荐使用 ReplicaSet模式取代了Master-Slaver模式,是一种互为主从的关系。Replica Set 将数据复制多份保存

    2024年01月22日
    浏览(39)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包