MongoDB主从+php实现

本文涉及的产品
云数据库 MongoDB,独享型 2核8GB
推荐场景:
构建全方位客户视图
简介:

环境

172.16.115.202   primary

172.16.111.171   secondary

172.16.115.157   secondary


一、MongoDB安装

1. yum下载安装mongodb

     扩展源http://repo.mongodb.org/yum/redhat/mongodb-org-3.0.repo

     mongodb-org-3.0.7-1.el6.x86_64.rpm #元数据包,它可以实现自动安装下面的4个组件包

     mongodb-org-mongos-3.0.7-1.el6.x86_64.rpm # mongod守护程序,以及相关的配置和初始化脚本

     mongodb-org-server-3.0.7-1.el6.x86_64.rpm # mongos守护程序

     mongodb-org-shell-3.0.7-1.el6.x86_64.rpm # ongo shell环境

     mongodb-org-tools-3.0.7-1.el6.x86_64.rpm # MongoDB工具


2. 编辑配置文件vim  /etc/mongod.conf

    1)去掉以下两行以#开头的注释,以防重启报错

         fork:true

         pidFilePath:/var/mongodb/mongod.pid


    2)bind_ip绑定多个IP,用逗号隔开,如监听全部,留空即可


3. 修改配置参数,启动mongd

    echo never > /sys/kernel/mm/transparent_hugepage/enabled

    echo never > /sys/kernel/mm/transparent_hugepage/defrag


    编辑vim /etc/security/limits.conf,加入内容:

    mongod soft nofile 64000

    mongod hard nofile 64000

    mongod soft nproc 32000

    mongod hard nproc 32000

    service mongd start

    注:启动过程较慢,这是它在写数据/var/lib/mongo,如果启动不了,mongod -f /etc/mongod.conf方式,可以看到报错



4. 编辑三台机器的MongoDB配置文件vim /etc/mongod.conf,重启

    内容:

    ##1)去掉replication的注释

    ##2)加入下面参数(注意首行留空2个空格,固定格式):

    ## 类似于二进制日志

       oplogSizeMB: 20

    ## 副本集名字

       replSetName: huangzhenping


5. 查看日志文件tail /var/log/mongodb/mongod.log

 wKioL1i-m8ThWU9gAACqp3ecICw925.png


6. 主上配置,搭建副本集   

    use admin # 主上进入admin库

    config={_id:"huangzhenping",members:[{_id:0,host:"172.16.115.202:27017"},{_id:1,host:"172.16.115.157:27017"},{_id:2,host:"172.16.111.171:27017"}]}  #配置机器

    rs.initiate(config)  #刷新

    rs.status()   #查看状态


 如下结果:出现三台机器的信息,主的状态已变为PRIMARY

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
> rs.initiate(config)
"ok"  : 1 }
huangzhenping:OTHER> rs.status()
{
         "set"  "huangzhenping" ,
         "date"  : ISODate( "2017-01-14T20:24:59.490Z" ),
         "myState"  : 1,
         "members"  : [
                 {
                         "_id"  : 0,
                         "name"  "172.16.115.202:27017" ,
                         "health"  : 1,
                         "state"  : 1,
                         "stateStr"  "PRIMARY" ,
                         "uptime"  : 297,
                         "optime"  : Timestamp(1484425453, 1),
                         "optimeDate"  : ISODate( "2017-01-14T20:24:13Z" ),
                         "electionTime"  : Timestamp(1484425455, 1),
                         "electionDate"  : ISODate( "2017-01-14T20:24:15Z" ),
                         "configVersion"  : 1,
                         "self"  true
                 },
                 {
                         "_id"  : 1,
                         "name"  "172.16.115.157:27017" ,
                         "health"  : 1,
                         "state"  : 2,
                         "stateStr"  "SECONDARY" ,
                         "uptime"  : 45,
                         "optime"  : Timestamp(1484425453, 1),
                         "optimeDate"  : ISODate( "2017-01-14T20:24:13Z" ),
                         "lastHeartbeat"  : ISODate( "2017-01-14T20:24:57.851Z" ),
                         "lastHeartbeatRecv"  : ISODate( "2017-01-14T20:24:58.343Z" )                  ,
                         "pingMs"  : 0,
                         "configVersion"  : 1
                 },
                 {
                         "_id"  : 2,
                         "name"  "172.16.111.171:27017" ,
                         "health"  : 1,
                         "state"  : 2,
                         "stateStr"  "SECONDARY" ,
                         "uptime"  : 45,
                         "optime"  : Timestamp(1484425453, 1),
                         "optimeDate"  : ISODate( "2017-01-14T20:24:13Z" ),
                         "lastHeartbeat"  : ISODate( "2017-01-14T20:24:57.863Z" ),
                         "lastHeartbeatRecv"  : ISODate( "2017-01-14T20:24:58.262Z" )                  ,
                         "pingMs"  : 1,
                         "configVersion"  : 1
                 }
         ],
         "ok"  : 1
}
huangzhenping:PRIMARY>


    注:

       1)如执行rs.status()命令,没有发现三台机器,需手动执行添加

            rs.add("172.16.115.157")

            rs.add("172.16.111.171")


       2)如从机的状态为"stateStr":"STARTUP",则需执行:

            var config={_id:"huangzhenping",members:[{_id:0,host:"172.16.115.202:27017"},{_id:1,host:"172.16.115.157:27017"},{_id:2,host:"172.16.111.171:27017"}]}

            rs.initiate(config)


7. 从上登录,状态已变为:SECONDARY

 wKioL1i-m-mhQhKDAABG26tPprQ067.png



二、MongoDB主从测试

1. mongodb副本集测试

    1)主上建库,建集合

     use mydb

     db.createCollection('testA')

     show dbs

     show tables

 wKiom1i-ndfhqvAAAAAS4mtdZl8376.png


    2)从上查看,已成功同步库和集合

     rs.slaveOk()

     show dbs

 wKiom1i-ngOy7R43AAAes6jLBh4261.png



2. 副本集更改权重,模拟主宕机

   1)主上设置不同的权重,并查看

       cfg = rs.conf()

       cfg.members[0].priority = 3

       cfg.members[1].priority = 2

       cfg.members[2].priority = 1

       rs.reconfig(cfg)

       rs.config()


       查看生效的权重:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
huangzhenping:PRIMARY> rs.config()
{
         "_id"  "huangzhenping" ,
         "version"  : 2,
         "members"  : [
                 {
                         "_id"  : 0,
                         "host"  "172.16.115.202:27017" ,
                         "arbiterOnly"  false ,
                         "buildIndexes"  true ,
                         "hidden"  false ,
                         "priority"  : 3,
                         "tags"  : {
                         },
                         "slaveDelay"  : 0,
                         "votes"  : 1
                 },
                 {
                         "_id"  : 1,
                         "host"  "172.16.115.157:27017" ,
                         "arbiterOnly"  false ,
                         "buildIndexes"  true ,
                         "hidden"  false ,
                         "priority"  : 2,
                         "tags"  : {
                         },
                         "slaveDelay"  : 0,
                         "votes"  : 1
                 },
                 {
                         "_id"  : 2,
                         "host"  "172.16.111.171:27017" ,
                         "arbiterOnly"  false ,
                         "buildIndexes"  true ,
                         "hidden"  false ,
                         "priority"  : 1,
                         "tags"  : {
                         },
                         "slaveDelay"  : 0,
                         "votes"  : 1
                 }
         ],
         "settings"  : {
                 "chainingAllowed"  true ,
                 "heartbeatTimeoutSecs"  : 10,
                 "getLastErrorModes"  : {
                 },
                 "getLastErrorDefaults"  : {
                         "w"  : 1,
                         "wtimeout"  : 0
                 }
         }
}


2) 主上禁用27017端口,模拟主宕机

        iptables -I INPUT -p tcp --dport 27017 -j DROP

        原主上:已连接失败

  wKiom1i-ninBM260AAA0_3eFTrE669.png


       原一台从机:状态已变为PRIMARY

  wKioL1i-nkiiGMIwAAAOaCuu-O4510.png  


       rs.status()查看状态:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
huangzhenping:PRIMARY> rs.status()
{
         "set"  "huangzhenping" ,
         "date"  : ISODate( "2017-01-22T15:48:15.453Z" ),
         "myState"  : 1,
         "members"  : [
                 {
                         "_id"  : 0,
                         "name"  "172.16.115.202:27017" ,
                         "health"  : 0,
                         "state"  : 8,
                         "stateStr"  "(not reachable/healthy)" ,
                         "uptime"  : 0,
                         "optime"  : Timestamp(0, 0),
                         "optimeDate"  : ISODate( "1970-01-01T00:00:00Z" ),
                         "lastHeartbeat"  : ISODate( "2017-01-22T15:48:14.551Z" ),
                         "lastHeartbeatRecv"  : ISODate( "2017-01-22T15:48:14.632Z" ),
                         "pingMs"  : 0,
                         "lastHeartbeatMessage"  "Failed attempt to connect to 172.16.115.202:27017; couldn't connect to server 172.16.115.202:27017 (172.16.115.202), connection attempt failed" ,
                         "configVersion"  : -1
                 },
                 {
                         "_id"  : 1,
                         "name"  "172.16.115.157:27017" ,
                         "health"  : 1,
                         "state"  : 1,
                         "stateStr"  "PRIMARY" ,
                         "uptime"  : 16333,
                         "optime"  : Timestamp(1484429320, 1),
                         "optimeDate"  : ISODate( "2017-01-14T21:28:40Z" ),
                         "electionTime"  : Timestamp(1485100022, 1),
                         "electionDate"  : ISODate( "2017-01-22T15:47:02Z" ),
                         "configVersion"  : 2,
                         "self"  true
                 },
                 {
                         "_id"  : 2,
                         "name"  "172.16.111.171:27017" ,
                         "health"  : 1,
                         "state"  : 2,
                         "stateStr"  "SECONDARY" ,
                         "uptime"  : 5989,
                         "optime"  : Timestamp(1484429320, 1),
                         "optimeDate"  : ISODate( "2017-01-14T21:28:40Z" ),
                         "lastHeartbeat"  : ISODate( "2017-01-22T15:48:14.751Z" ),
                         "lastHeartbeatRecv"  : ISODate( "2017-01-22T15:48:14.749Z" ),
                         "pingMs"  : 0,
                         "lastHeartbeatMessage"  "could not find member to sync from" ,
                         "configVersion"  : 2
                 }
         ],
         "ok"  : 1
}



3)新主上,创建一个库和集合

     use mydb2

     db.createCollection('testB')

 wKiom1i-noTgxEqAAAAbdXTAOks526.png

 


4)恢复旧主,则自动切换为MASTER状态,并同步自己离线时新主上创建的库

      iptables -D INPUT -p tcp --dport 27017 -j DROP

 wKioL1i-npHw7nd2AAAerGCNFvM913.png




三、MongoDB结合php

1. 下载安装mongo扩展模块

     wget https://github.com/mongodb/mongo-php-driver-legacy/archive/master.zip

     unzip mongo-php-driver-legacy-master.zip

     cd mongo-php-driver-legacy-master

     /usr/bin/phpize

     ./configure --with-php-config=/usr/bin/php-config

     make;make install 

     wKiom1i-nv-SmKznAAAltOOeocM236.png


2. 编辑php配置文件vim /etc/php.ini,加载扩展模块

 wKiom1i-nw3R-zBHAAAKL5aTSLI099.png 


 wKioL1i-nxmzRggwAAARBv57UFU659.png



3. 编辑测试文件 vim /usr/local/apache2/htdocs/1.php

    内容:

1
2
3
4
5
6
7
8
<?php
//  连接到mongodb
$m = new MongoClient();
echo  "Connection to database successfully" ;
//  选择一个数据库
$db = $m->mydb;
echo  "Database mydb selected" ;
?>


4. 测试 curl localhost/1.php

 wKiom1i-nyyiIAVDAAAOmD6yFek249.png










本文转自 huangzp168 51CTO博客,原文链接:http://blog.51cto.com/huangzp/1904088,如需转载请自行联系原作者
相关实践学习
MongoDB数据库入门
MongoDB数据库入门实验。
快速掌握 MongoDB 数据库
本课程主要讲解MongoDB数据库的基本知识,包括MongoDB数据库的安装、配置、服务的启动、数据的CRUD操作函数使用、MongoDB索引的使用(唯一索引、地理索引、过期索引、全文索引等)、MapReduce操作实现、用户管理、Java对MongoDB的操作支持(基于2.x驱动与3.x驱动的完全讲解)。 通过学习此课程,读者将具备MongoDB数据库的开发能力,并且能够使用MongoDB进行项目开发。 &nbsp; 相关的阿里云产品:云数据库 MongoDB版 云数据库MongoDB版支持ReplicaSet和Sharding两种部署架构,具备安全审计,时间点备份等多项企业能力。在互联网、物联网、游戏、金融等领域被广泛采用。 云数据库MongoDB版(ApsaraDB for MongoDB)完全兼容MongoDB协议,基于飞天分布式系统和高可靠存储引擎,提供多节点高可用架构、弹性扩容、容灾、备份回滚、性能优化等解决方案。 产品详情: https://www.aliyun.com/product/mongodb
目录
相关文章
|
NoSQL Cloud Native MongoDB
MongoDB 主从集群 2
MongoDB 主从集群 2
|
28天前
|
NoSQL MongoDB PHP
MongoDB PHP
10月更文挑战第19天
32 2
MongoDB PHP
|
28天前
|
NoSQL 安全 Linux
MongoDB PHP 扩展
10月更文挑战第19天
12 0
MongoDB PHP 扩展
|
4月前
|
消息中间件 NoSQL 中间件
MongoDB多数据中心的主从结构
【7月更文挑战第3天】
43 0
|
4月前
|
消息中间件 NoSQL 中间件
MongoDB主从结构、仲裁节点
【7月更文挑战第2天】
64 0
|
存储 NoSQL 网络协议
MongoDB 主从集群 1
MongoDB 主从集群 1
|
6月前
|
运维 NoSQL Linux
MongoDB详解(六)——MongoDB主从同步配置
MongoDB详解(六)——MongoDB主从同步配置
283 5
|
NoSQL MongoDB 数据库
【mongo 系列】mongodb 学习九,MongoDB 主从集群 2
继续咱们 mongodb 集群的学习和分享 上次分享了 mongodb 主从集群的同步机制(oplog),心跳机制,这次我们继续看看选举机
128 0
|
存储 NoSQL 网络协议
【mongo 系列】mongodb 学习八,MongoDB 主从集群 1
说到集群,生产环境中很多服务都会进行集群部署,那么 mongodb 的集群都有哪些知识点需要掌握呢
166 0
|
PHP
php实现数字格式化,数字每三位加逗号的功能函数169856420=&gt;169,856,420
php实现数字格式化,数字每三位加逗号的功能函数169856420=&gt;169,856,420
216 0
下一篇
无影云桌面