加入重连机制忽略日志记录错误

This commit is contained in:
2025-03-05 14:10:03 +08:00
parent a2155976f3
commit a15345adeb
5 changed files with 96 additions and 26 deletions

View File

@@ -1,3 +1,5 @@
import 'dart:io';
import 'package:EasyDartModule/base/database/DataBase.dart';
import 'package:mongo_dart/mongo_dart.dart';
@@ -7,16 +9,26 @@ class MongoDb implements DataBase {
MongoDb(this.config)
: db = Db(
"mongodb://${config.userName}:${config.password}@${config.host}/${config.dataBase}?authSource=admin") {
connect(false);
}
void connect(reconnect) {
if (reconnect) {
print("尝试重连MongoDb");
}
Future.delayed(Duration(seconds: 1), () async {
do {
try {
await db.open();
print('Connected successfully!');
} catch (e) {
print('Connection error: $e');
await Future.delayed(Duration(seconds: 1));
}
} while (!db.isConnected);
try {
await db.open();
print('MongoDb Connected successfully!');
//定时检测数据库是否断开
do {
await Future.delayed(Duration(seconds: 5));
} while (db.isConnected);
connect(true);
} catch (e) {
print('MongoDb Connection error: $e');
connect(reconnect);
}
});
}