MongoDB 部署副本集 + 代码中开启事务
首先,指定副本名称:
vim /etc/mongod.conf
replication:
replSetName: shard1
在replication里面加入副本名称,多个相同副本,应该使用同样的名称
如果要修改mongodb占用的内存,可以这样设置:
storage: wiredTiger: engineConfig: cacheSizeGB: 1
进入mongo客户端:
mongosh 127.0.0.1:27017
rs.initiate({ _id:"shard1", "members":[ { _id:0, "host":"192.168.11.137:27017" }, { _id:1, "host":"192.168.11.138:27017" }, { _id:2, "host":"192.168.11.139:27017" }] })
rs.status() 可以看到当前状态
db.isMaster() 查看谁成为了master
用MongoClient连接这几个副本集:
var client = new MongoClient("mongodb://192.168.11.137:27017,192.168.11.138:27017,192.168.11.139:27017");
用了副本集,就可以使用事务了:
var client = new MongoClient("mongodb://192.168.11.137:27017,192.168.11.138:27017,192.168.11.139:27017"); var session = client.StartSession(); session.StartTransaction(); var database = client.GetDatabase("MyTestDB"); var collection = database.GetCollection<UserInfo>("UserInfo"); collection.InsertOne( session, new UserInfo { Name = "Jack", CreateTime = DateTime.Now, }); session.CommitTransaction();