MongoDB的副本集,我的理解就是自带故障转移的主从复制。

集群的入口还是主节点,数据也是从主节点分发,这个和MySQL都是一致的。
和MySQL Master-Slave不一样的是,副本集记录各个节点的心跳信息。
一旦主节点不可用,其余的节点会推举一个新的主节点,进行故障转移,而这些操作对于应用是透明的。

mongodb新建副本集的时候,从节点必须是空库,没有任何数据。
测试环境如下
192.168.25.128 主节点
192.168.25.129 从节点
192.168.25.130 从节点
配置文件如下(三个节点都是同样的配置)
dbpath=/home/lihuilin/Desktop/data
smallfiles=true
replSet=mvbox
其中replSet是集群的名称
三个节点启动之后,在主节点输入集群配置
-
config = { _id:"mvbox", members:[
-
{_id:0,host:"192.168.25.128:27017"},
-
{_id:1,host:"192.168.25.129:27017"},
-
{_id:2,host:"192.168.25.130:27017"}]
-
}
-
rs.initiate(config);
结果如下
查看自己是否是主节点

查看集群状态
使用JAVA程序测试MongoDB集群
-
import java.util.*;
-
import com.mongodb.*;
-
-
public class MongoTest {
-
public static void main(String[] args) {
-
-
try {
-
List<ServerAddress> addresses = new ArrayList<ServerAddress>();
-
ServerAddress address1 = new ServerAddress("192.168.25.128" , 27017);
-
ServerAddress address2 = new ServerAddress("192.168.25.129" , 27017);
-
ServerAddress address3 = new ServerAddress("192.168.25.130" , 27017);
-
addresses.add(address1);
-
addresses.add(address2);
-
addresses.add(address3);
-
-
MongoClient client = new MongoClient(addresses);
-
DB db = client.getDB( "mvbox");
-
DBCollection coll = db.getCollection( "song");
-
-
BasicDBObject object = new BasicDBObject();
-
object.append( "s1", "test1" );
-
-
coll.insert(object);
-
-
DBCursor dbCursor = coll.find();
-
-
while (dbCursor.hasNext()) {
-
DBObject dbObject = dbCursor.next();
-
System. out.println(dbObject.toString());
-
}
-
-
} catch (Exception e) {
-
e.printStackTrace();
-
}
-
-
}
-
-
}
插入一条记录
然后将主节点关机,模拟故障
原来129的从节点被选举为新的主节点。
再次执行JAVA程序,
可以看到前端的JAVA程序不受影响.
参考:
http://www.lanceyan.com/tech/mongodb/mongodb_repset1.html
http://www.cnblogs.com/huangxincheng/archive/2012/02/18/2356595.html
http://www.w3cschool.cc/mongodb/mongodb-tutorial.html
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/29254281/viewspace-1161835/
,如需转载,请注明出处,否则将追究法律责任。