在使用多文档交易时,我遇到很多麻烦。其中之一恰好是-每当[同一个事务中]同一文档上有多个更新时,Mongo都会抛出一个奇怪的错误“ com.mongodb.MongoCommandException: Command failed with error 251 (NoSuchTransaction): 'Transaction 1 has been aborted.' on server .....
”。我朝着可见的方向看了它,并调整了诸如“
WriteConcern.MAJORITY,ReadPreference.PRIMARY,ReadConcern.SNAPSHOT。
我正在使用Java驱动程序,并且交易开始的代码段如下所示
TransactionOptions transactionOptions = TransactionOptions.builder()
.writeConcern(WriteConcern.MAJORITY)
.readPreference(ReadPreference.primary())
.readConcern(ReadConcern.SNAPSHOT)
.build();
ClientSessionOptions clientSessionOptions = ClientSessionOptions
.builder()
.defaultTransactionOptions(transactionOptions)
.build();
this.session = mongo.startSession(clientSessionOptions);
this.session.startTransaction(transactionOptions);
有人对此错误有想法吗?
答案 0 :(得分:2)
为了获得有关该错误的更多上下文,您需要检查Mongodb的日志。
在Mongo shell mongo
中,运行show log global
,您将看到事务失败的原因。
就我而言,由于以下原因而失败:
[startPeriodicThreadToAbortExpiredTransactions] Aborting transaction with
txnNumber 1 on session ea5e8c8d-ecc2-47ca-8901-55a43143a809 because it has
been running for longer than 'transactionLifetimeLimitSeconds'
这看起来像是MongoDB中的错误,因为它应该引发transactionLifetimeLimitSeconds
错误,或者至少告诉您是什么问题。
答案 1 :(得分:0)
该事务可能包括修改数据库目录的操作。由于在不存在的集合上执行insert
操作,导致遇到相同的错误。提交事务时发生251
错误。
my-rs:PRIMARY> use mytest
switched to db mytest
my-rs:PRIMARY> show collections
my-rs:PRIMARY> session.startTransaction()
my-rs:PRIMARY> session.getDatabase('mytest').newcollection.insert({"a":"b"});
WriteCommandError({
"operationTime" : Timestamp(1554822412, 1),
"ok" : 0,
"errmsg" : "Cannot create namespace mytest.newcollection in multi-document transaction.",
"code" : 263,
"codeName" : "OperationNotSupportedInTransaction",
"$clusterTime" : {
"clusterTime" : Timestamp(1554822412, 1),
"signature" : {
"hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
"keyId" : NumberLong(0)
}
}
})
my-rs:PRIMARY> session.commitTransaction()
2019-04-09T15:07:04.695+0000 E QUERY [js] Error: command failed: {
"errorLabels" : [
"TransientTransactionError"
],
"operationTime" : Timestamp(1554822422, 1),
"ok" : 0,
"errmsg" : "Transaction 8 has been aborted.",
"code" : 251,
"codeName" : "NoSuchTransaction",
"$clusterTime" : {
"clusterTime" : Timestamp(1554822422, 1),
"signature" : {
"hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
"keyId" : NumberLong(0)
}
}
} :
_getErrorWithCode@src/mongo/shell/utils.js:25:13
doassert@src/mongo/shell/assert.js:18:14
_assertCommandWorked@src/mongo/shell/assert.js:536:17
assert.commandWorked@src/mongo/shell/assert.js:620:16
commitTransaction@src/mongo/shell/session.js:942:17
@(shell):1:1
my-rs:PRIMARY>
请参阅https://docs.mongodb.com/manual/core/transactions/#restricted-operations