Skip to content

Commit

Permalink
perf[id]: catch getIncrementIdFromMongo exception
Browse files Browse the repository at this point in the history
  • Loading branch information
jaysunxiao committed Sep 22, 2024
1 parent a3d6b71 commit 6dd5b3a
Showing 1 changed file with 14 additions and 12 deletions.
26 changes: 14 additions & 12 deletions orm/src/main/java/com/zfoo/orm/util/MongoIdUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}

Expand Down

0 comments on commit 6dd5b3a

Please sign in to comment.