加入重连机制忽略日志记录错误
This commit is contained in:
@@ -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);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user