一 副本集:
实现集群搭建,冗余备份,故障自动切换,读写分离,java访问集群。
1 搭建
a.conf:
dbpath=/opt/data/mongo100a
port=1111
bind_ip=192.168.1.100
replSet=child/192.168.1.100:2222
# /opt/mongo/mongo100a/bin/mongod --config /opt/mongo/replset/a.conf
dbpath=/opt/data/mongo100b
port=2222
bind_ip=192.168.1.100
replSet=child/192.168.1.100:3333
# /opt/mongo/mongo100b/bin/mongod --config /opt/mongo/replset/b.conf
dbpath=/opt/data/mongo100c
port=3333
bind_ip=192.168.1.100
replSet=child/192.168.1.100:1111
# /opt/mongo/mongo100c/bin/mongod --config /opt/mongo/replset/c.conf
# /opt/mongo/mongo100a/bin/mongo 192.168.1.100:1111
# /opt/mongo/mongo100b/bin/mongo 192.168.1.100:2222
# /opt/mongo/mongo100c/bin/mongo 192.168.1.100:3333
任意一台,初始化副本集
[root@Master ~]# /opt/mongo/mongo100b/bin/mongo 192.168.1.100:2222
use admin
db.runCommand({"replSetReconfig" : {
"_id" : "child",
"members" : [
{
"_id" : 1,
"host" : "192.168.1.100:1111"
},
{
"_id" : 2,
"host" : "192.168.1.100:2222"
},
{
"_id" : 3,
"host" : "192.168.1.100:3333"
}
]}})
local.oplog.r
初始化完,选出活跃点,不再有连接不上同伴的提示。如下:
Sun Sep 22 05:48:21.340 [rsStart] trying to contact 192.168.1.100:2222
Sun Sep 22 05:48:21.342 [rsStart] couldn't connect to 192.168.1.100:2222: couldn't connect to server 192.168.1.100:2222
Sun Sep 22 05:48:21.344 [rsStart] replSet info Couldn't load config yet. Sleeping 20sec and will try again.
初始化后显示Sun Sep 22 04:36:27.135 [initandlisten] connection accepted from 192.168.1.100:33909 #13 (2 connections now open)
查看状态:
child:SECONDARY> rs.status()
{
"set" : "child",
"date" : ISODate("2013-09-21T20:40:12Z"),
"myState" : 2,
"syncingTo" : "192.168.1.100:2222",
"members" : [
{
"_id" : 1,
"name" : "192.168.1.100:1111",
"health" : 1,
"state" : 2,
"stateStr" : "SECONDARY",
"uptime" : 373,
"optime" : Timestamp(1379795635, 1),
"optimeDate" : ISODate("2013-09-21T20:33:55Z"),
"lastHeartbeat" : ISODate("2013-09-21T20:40:12Z"),
"lastHeartbeatRecv" : ISODate("2013-09-21T20:40:11Z"),
"pingMs" : 0,
"syncingTo" : "192.168.1.100:2222"
},
{
"_id" : 2,
"name" : "192.168.1.100:2222",
"health" : 1,
"state" : 1,
"stateStr" : "PRIMARY",
"uptime" : 373,
"optime" : Timestamp(1379795635, 1),
"optimeDate" : ISODate("2013-09-21T20:33:55Z"),
"lastHeartbeat" : ISODate("2013-09-21T20:40:12Z"),
"lastHeartbeatRecv" : ISODate("2013-09-21T20:40:12Z"),
"pingMs" : 1
},
{
"_id" : 3,
"name" : "192.168.1.100:3333",
"health" : 1,
"state" : 2,
"stateStr" : "SECONDARY",
"uptime" : 1277,
"optime" : Timestamp(1379795635, 1),
"optimeDate" : ISODate("2013-09-21T20:33:55Z"),
"self" : true
}
],
"ok" : 1
}
child:PRIMARY> use testdb
switched to db testdb
child:PRIMARY> db.testdb.insert({name:"thrillerzw",age:27})
child:SECONDARY> show dbs;
local 0.09375GB
testdb 0.0625GB
child:SECONDARY> use testdb
switched to db testdb
child:SECONDARY> db.testcol.find()
error: { "$err" : "not master and slaveOk=false", "code" : 13435 }
重新配置报错:
"errmsg" : "local.oplog.rs is not empty on the initiating member. cannot initiate."
db.runCommand({replSetReconfig: config});
{
"startupStatus" : 1,
"ok" : 0,
"errmsg" : "loading local.system.replset config (LOADINGCONFIG)"
}
解决: Reconfigure the replicaset with the new configuration
> rs.config()
{
"_id" : "child",
"version" : 1,
"members" : [
{
"_id" : 1,
"host" : "192.168.1.100:1111"
},
{
"_id" : 2,
"host" : "192.168.1.100:2222"
},
{
"_id" : 3,
"host" : "192.168.1.100:3333"
}
]
}
> var cfg = rs.config()
> cfg.members = [
... {
... "_id" : 1,
... "host" : "192.168.1.100:1111"
... },
... {
... "_id" : 2,
... "host" : "192.168.1.100:2222"
... },
{
... {
... "_id" : 3,
... "host" : "192.168.1.100:3333"
... }
... ]
[
{
"_id" : 1,
"host" : "192.168.1.100:1111"
},
{
"_id" : 2,
"host" : "192.168.1.100:2222"
},
{
"_id" : 3,
"host" : "192.168.1.100:3333"
}
]
> rs.reconfig(cfg , {force : true})
{
"msg" : "will try this config momentarily, try running rs.conf() again in a few seconds",
"ok" : 1
}
> rs.conf()
{
"_id" : "child",
"version" : 96789,
"members" : [
{
"_id" : 1,
"host" : "192.168.1.100:1111"
},
{
"_id" : 2,
"host" : "192.168.1.100:2222"
},
{
"_id" : 3,
"host" : "192.168.1.100:3333"
}
]
}
rs.status()查看正确,重连mongo shell就好了,不用重启mongod。
只剩一个节点活着:Exception in thread "main" com.mongodb.MongoException: can't find a master
child:SECONDARY> db.getMongo().setSlaveOk() 设置以后所有从库都可读。
添加一台服务器:
# /opt/mongo/mongo101a/bin/mongod --config /opt/mongo/replset/a.conf
在活跃节点上执行
child:PRIMARY> rs.add("192.168.1.101:1111")
{ "ok" : 1 }
如果要删除某一个节点可以执行rs.remove(“主机名:端口号”)
PRIMARY修改优先级:
cfg = rs.conf()
cfg.members[3].priority = 0
rs.reconfig(cfg)
2 java 调用
package mongo; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.List; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBCursor; import com.mongodb.DBObject; import com.mongodb.Mongo; import com.mongodb.MongoException; import com.mongodb.MongoOptions; import com.mongodb.ReadPreference; import com.mongodb.ReplicaSetStatus; import com.mongodb.ServerAddress; /** * MongoDB 连接器 * * @author thrillerzw */ public class MongoConn { private static Mongo[] mongos = new Mongo[10]; private static short mongoCount = 0; private static DB db = null; static Mongo m; static Mongo mread; static { List<ServerAddress> addresslist = new ArrayList<ServerAddress>(); try { addresslist.add(new ServerAddress("192.168.1.100:1111")); addresslist.add(new ServerAddress("192.168.1.100:2222")); } catch (UnknownHostException e) { System.err.println("address check error."); System.exit(-1); } List<ServerAddress> readAddresslist = new ArrayList<ServerAddress>(); try { readAddresslist.add(new ServerAddress("192.168.1.101:1111")); readAddresslist.add(new ServerAddress("192.168.1.100:3333")); } catch (UnknownHostException e) { System.err.println("address check error."); System.exit(-1); } MongoOptions options = new MongoOptions(); options.autoConnectRetry = true; options.connectionsPerHost = 20; options.connectTimeout = 6000; options.maxAutoConnectRetryTime = 12000; options.maxWaitTime = 12000; options.socketKeepAlive = true; options.socketTimeout = 2000; try { m = new Mongo(addresslist, options); mread=new Mongo(readAddresslist,options); } catch (MongoException e) { System.err.println("mongo create error."); System.exit(-1); } } public final static Mongo getMongo() { return m; } public final static DB getDB(String dbName) { Mongo mongo = getMongo(); if (db == null && mongo != null) { try { db = mongo.getDB(dbName); } catch (Exception e) { e.printStackTrace(); } } return db; } public static void main(String[] args) { Mongo mongo= getMongo() ; ReplicaSetStatus replicaSetStatus=mongo.getReplicaSetStatus(); ReadPreference readPreference =mongo.getReadPreference(); DB readDb = mread.getDB("testdb"); DB db=getDB("testdb"); DBCollection dBCollection =db.getCollection("testcol"); DBCursor dBCursor =dBCollection.find(); while(dBCursor.hasNext()){ DBObject dBObject=dBCursor.next(); System.out.println(dBObject.get("name")+" "+dBObject.get("age")); } System.out.println("----------"); DBCollection rdBCollection =db.getCollection("testcol"); DBCursor rdBCursor =dBCollection.find(); while(rdBCursor.hasNext()){ DBObject dBObject=rdBCursor.next(); System.out.println(dBObject.get("name")+" "+dBObject.get("age")); } try { Mongo m2 = new Mongo("192.168.1.100:3333"); DB db2=m2.getDB("testdb"); db2.slaveOk(); DBCollection c2=db2.getCollection("testcol"); DBCursor dBCursor2 =c2.find(); //Exception in thread "main" com.mongodb.MongoException: not talking to master and retries used up //加db2.slaveOk();解决。 while(dBCursor2.hasNext()){ DBObject dBObject=dBCursor2.next(); System.out.println(dBObject.get("name")+" "+dBObject.get("age")); } } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
三:乱七八糟
可变列,灵活。
bson格式跟json相同,数据类型多。
shell封装了js引擎,可以用for(var i=0...)在 shell批量插入。
强硬的更新会替换掉老的文档,想要的是局部更新。
remove不会删除索引且效率低,用db.集合名.drop()更好。
saveOrUpdate: update({查询器},{修改器},true);
批量更新$set update({查询器},{修改器},false,true);
addToSet 和each判断式批量导入。
不支持多表关联查询,嵌套查询。单表可以使用正则查询,比sql强大。
查询符在对象内部,更新符在对象外部。
$size只能等于,不能用其它比较运算符,如大于,小于。可以给表加数组的大小字段,注意更新。
[root@Slave1 bin]# ./mongo 127.0.0.1:27017/admin
show dbs;
use testdb;
db.thrillerzw.insert({name:"testName2"});
db.thrillerzw.findOne();
db.thrillerzw.find();
db.thrillerzw.help();