perf[id]: catch getIncrementIdFromMongo exception

This commit is contained in:
jaysunxiao committed 2024-09-22 14:57:37 +08:00
1 parent a3d6b717df
commit 6dd5b3ac65
1 file changed
+14 -12
@@ -57,23 +57,25 @@ public abstract class MongoIdUtils {
public static long getIncrementIdFromMongo(String collectionName, String documentName) { public static long getIncrementIdFromMongo(String collectionName, String documentName) {
var collection = OrmContext.getOrmManager().getCollection(collectionName); var collection = OrmContext.getOrmManager().getCollection(collectionName);
var document = collection.findOneAndUpdate(Filters.eq("_id", documentName) try {
, new Document("$inc", new Document(COUNT, 1L))); var document = collection.findOneAndUpdate(Filters.eq("_id", documentName), new Document("$inc", new Document(COUNT, 1L)));
if (document != null) {
if (document != null) { return document.getLong("count") + 1;
return document.getLong("count") + 1; }
} catch (Throwable t) {
logger.info("getIncrementIdFromMongo collection:[{}] document:[{}] default error", collectionName, documentName, t);
} }
Bson query = Filters.eq("_id", documentName); var query = Filters.eq("_id", documentName);
Document inc = new Document("$inc", new Document(COUNT, 1L)); var inc = new Document("$inc", new Document(COUNT, 1L));
Document setOnInsert = new Document("$setOnInsert", new Document("_id", documentName)); var setOnInsert = new Document("$setOnInsert", new Document("_id", documentName));
// 报错后重试创建并获取id,在大并发create的时候mongodb总是会报错一次“duplicate key error!” 所以重试一次 // 报错后重试创建并获取id,在大并发create的时候mongodb总是会报错一次“duplicate key error!” 所以重试一次
for (int i = 0; i < 2; i++) { for (var i = 0; i < 3; i++) {
try { try {
document = collection.findOneAndUpdate(query, Updates.combine(inc, setOnInsert), new FindOneAndUpdateOptions().upsert(true)); var document = collection.findOneAndUpdate(query, Updates.combine(inc, setOnInsert), new FindOneAndUpdateOptions().upsert(true));
return null == document ? INIT_ID : document.getLong(COUNT) + 1; return null == document ? INIT_ID : document.getLong(COUNT) + 1;
} catch (Throwable throwable) { } catch (Throwable t) {
logger.info("getIncrementIdFromMongo error! retry! ", throwable); logger.info("getIncrementIdFromMongo collection:[{}] document:[{}] retry error! ", collectionName, documentName, t);
} }
} }