我想创造功能。第一个是连接到数据库,如果第一个失败,第二个是完全重新连接。
在我的实验中,我在开始时关闭数据库以使connect
块失败并调用重新连接块。之后我打开数据库,并期待连接块会成功,但我得到了异常。
这是我的代码:
bool connect()
{
if(connection is null)
{
scope(failure) reconnect(); // call reconnect if fail
this.connection = mydb.lockConnection();
writeln("connection done");
return true;
}
else
return false;
}
void reconnect()
{
writeln("reconnection block");
if(connection is null)
{
while(!connect) // continue till connection will not be established
{
Thread.sleep(3.seconds);
connectionsAttempts++;
logError("Connection to DB is not active...");
logError("Reconnection to DB attempt: %s", connectionsAttempts);
connect();
}
if(connection !is null)
{
logWarn("Reconnection to DB server done");
}
}
}
日志(几秒钟后打开数据库):
reconnection block
reconnection block
connection done
Reconnection to DB server done
object.Exception@C:\Users\Dima\AppData\Roaming\dub\packages\vibe-d-0.7.30\vibe-d\source\vibe\core\drivers\libevent2.d(326): Failed to connect to host 194.87.235.42:3306: Connection timed out [WSAETIMEDOUT ]
我不明白为什么我在之后得到异常:Reconnection to DB server done