From 6dd5b3ac655f3cd224ccd9fa08b9906400a3327e Mon Sep 17 00:00:00 2001 From: jaysunxiao Date: Sun, 22 Sep 2024 14:57:37 +0800 Subject: [PATCH] perf[id]: catch getIncrementIdFromMongo exception --- .../java/com/zfoo/orm/util/MongoIdUtils.java | 26 ++++++++++--------- 1 file changed, 14 insertions(+), 12 deletions(-) diff --git a/orm/src/main/java/com/zfoo/orm/util/MongoIdUtils.java b/orm/src/main/java/com/zfoo/orm/util/MongoIdUtils.java index 83c88735..21d9f37a 100644 --- a/orm/src/main/java/com/zfoo/orm/util/MongoIdUtils.java +++ b/orm/src/main/java/com/zfoo/orm/util/MongoIdUtils.java @@ -57,23 +57,25 @@ public abstract class MongoIdUtils { public static long getIncrementIdFromMongo(String collectionName, String documentName) { var collection = OrmContext.getOrmManager().getCollection(collectionName); - var document = collection.findOneAndUpdate(Filters.eq("_id", documentName) - , new Document("$inc", new Document(COUNT, 1L))); - - if (document != null) { - return document.getLong("count") + 1; + try { + var document = collection.findOneAndUpdate(Filters.eq("_id", documentName), new Document("$inc", new Document(COUNT, 1L))); + if (document != null) { + return document.getLong("count") + 1; + } + } catch (Throwable t) { + logger.info("getIncrementIdFromMongo collection:[{}] document:[{}] default error", collectionName, documentName, t); } - Bson query = Filters.eq("_id", documentName); - Document inc = new Document("$inc", new Document(COUNT, 1L)); - Document setOnInsert = new Document("$setOnInsert", new Document("_id", documentName)); + var query = Filters.eq("_id", documentName); + var inc = new Document("$inc", new Document(COUNT, 1L)); + var setOnInsert = new Document("$setOnInsert", new Document("_id", documentName)); // 报错后重试创建并获取id,在大并发create的时候mongodb总是会报错一次“duplicate key error!” 所以重试一次 - for (int i = 0; i < 2; i++) { + for (var i = 0; i < 3; i++) { 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; - } catch (Throwable throwable) { - logger.info("getIncrementIdFromMongo error! retry! ", throwable); + } catch (Throwable t) { + logger.info("getIncrementIdFromMongo collection:[{}] document:[{}] retry error! ", collectionName, documentName, t); } }