一、bug背景
併發場景,對mongodb某一collection的某一條數據進行upsert操作。
二、報錯error
org.springframework.dao.DuplicateKeyException: Write failed with error code 11000 and error message 'E11000 duplicate key error collection: XXX.XXX index: _id_ dup key: { : "XXX" }'; nested exception is com.mongodb.DuplicateKeyException: Write failed with error code 11000 and error message 'E11000 duplicate key error collection: XXX.XXX index: _id_ dup key: { : "XXX" }'
at org.springframework.data.mongodb.core.MongoExceptionTranslator.translateExceptionIfPossible(MongoExceptionTranslator.java:73)
at org.springframework.data.mongodb.core.MongoTemplate.potentiallyConvertRuntimeException(MongoTemplate.java:2146)
at org.springframework.data.mongodb.core.MongoTemplate.execute(MongoTemplate.java:484)
at org.springframework.data.mongodb.core.MongoTemplate.doUpdate(MongoTemplate.java:1156)
at org.springframework.data.mongodb.core.MongoTemplate.upsert(MongoTemplate.java:1118)
三、問題排查
百思不得其姐,在更新條件只有一項,即主鍵_id,進行upsert操作爲什麼會有主鍵重複的問題的呢?
經過短暫的排查,發現了問題所在,mongo庫該條數據的更新時間與報錯時間是大致保持一致的。
真正的原因應該是這樣的,兩條相同的數據併發進行upsert操作,當同時查詢到mongo庫裏數據不存在時,會轉爲insert操作,這時插入一條數據成功後,另一條數據再次插入是就會出現主鍵重複的問題。
四、問題解決
結合實際業務場景,進行異常處理
try {
mongodbService.upsert(query, update, XXX.class);
} catch (DuplicateKeyException e) {
LoggerHelper.errAndEmail(getClass(),
"concurrent insert doc in the same primary key, doc : {}, e : {}", doc, e);
}