日期:2014-05-16  浏览次数:20409 次

MongoDB Replica Set配置

参考

?

http://www.mongodb.org/display/DOCS/Replica+Set+Tutorial

?


?

本实验三个节点,启动脚本如下

?

节点1

?

?

mkdir database\replset1
title: MongoDB replset1 Start by xiaofancn
bin\mongod.exe  --replSet group --port 27001 --rest --dbpath database\replset1

?

?

节点2

?

?

mkdir database\replset2
title: MongoDB replset2 Start by xiaofancn
bin\mongod.exe  --replSet group --port 27002 --rest --dbpath database\replset2

?

节点3

?

?

mkdir database\replset3
title: MongoDB replset3 Start by xiaofancn
bin\mongod.exe  --replSet group --port 27003 --rest --dbpath database\replset3

?

配置

?

?

bin\mongo localhost:27001

rs.initiate({
    _id : "group",
    members : [
        {_id : 0, host : "localhost:27001"},
        {_id : 1, host : "localhost:27002"},
        {_id : 2, host : "localhost:27003"}
    ]
});

rs.status();
?

使用rs.status(); 查看当前数据是不是primary 还是secondary,或者使用rs.isMaster();

?

测试代码

http://xiaofancn.iteye.com/blog/1163200

?

org.springframework.data.mongodb.examples.hello.AppConfig.java

?

主要修改代码

public @Bean
	MongoOperations mongoTemplate(Mongo mongo) {
		List<ServerAddress> setList = new ArrayList<ServerAddress>();
		MongoOptions options = new MongoOptions();
		try {
			setList.add(new ServerAddress("localhost", 27001));
			setList.add(new ServerAddress("localhost", 27002));
			setList.add(new ServerAddress("localhost", 27003));
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
		options.autoConnectRetry = true;
		mongo = new Mongo(setList,options);
		
		MongoTemplate mongoTemplate = new MongoTemplate(mongo, "test");
		return mongoTemplate;
	}

?

其他就可以调用App.java操作