(2019-7-2更新)7天后,我终于解决了这个问题。好吧,我的代码还可以,WTF,浪费了这么多时间。问题是我的团队使用阿里云(一家中国公司,如亚马逊、Azure),而 Mongodb 有很多版本,我们在一年前创建了数据库,那个版本会在处理截断时锁定数据库。
如果你有什么问题,希望我的经验能帮到你。
原谅我可怜的英语...
开发环境:3nodes的mongodb4.0集群,支持事务。.net core 2.2 (mongodb driver 2.7.2+) Robot 3T(mongod tool)
MongoDB 数据库将在启动事务后 60 秒被锁定,我认为问题可能出在锁定级别,但我已经尝试了 readconcern 或 writeconvern 的所有枚举,没有任何帮助。
这是一张图片:现在数据库已锁定,我无法在 Robot 3T 中查询数据,也无法在我的 Web 应用程序中查询。
我的意思是,在 commitTransaction/abortTransaction 之前,数据库将被锁定。如果交易量很大,30s 完成,实际上webapp 无法读取其他访问者的数据响应。
事实上,我的 webapp 的用户总是说,为什么你的应用运行这么慢(因为每个事务都会将数据库锁定 0.xx 秒)
TransactionOptions option = new TransactionOptions(readConcern: ReadConcern.Snapshot,writeConcern: WriteConcern.W1);
ClientSessionOptions so =new ClientSessionOptions();
so.DefaultTransactionOptions = option;
var session = _dataBase.Client.StartSession();
var products = _dataBase.GetCollection<Product>("products");
var TV = new Product { Description = "Television", SKU = 4001, Price = 2000 };
session.StartTransaction(option);
try
{
products.InsertOne(session, TV);
// after the sentence , database will be locked
// before commitTransaction, the webapp cannot response, like Robot 3T, // looks like the database is locked
session.CommitTransaction();