[英]Android Studio, Db connection error: Something unusual has occurred to cause the driver to fail. Please report this exception
[英]Exception after connection to DB with mysql-native driver
我想创建功能。 第一个是连接到数据库,第二个是如果第一个失败则完全重新连接。
在我的实验中,我在开始时关闭 DB 以使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
这里有两个主要问题。
首先,根本不需要自动重试。 如果它第一次不起作用,并且你没有改变任何东西,那么做同样的事情就没有理由第二次突然起作用。 如果您的网络如此不可靠,那么您的问题就会大得多。
其次,如果您无论如何都要自动重试,那么代码将不起作用:
一方面, reconnect
connect
在每次失败时调用connect
TWICE:一次在循环体的末尾,然后立即再次进入循环条件,无论连接是否成功。 这可能不是你想要的。
但更重要的是,你有一个潜在的无限递归:如果失败, connect
调用reconnect
。 然后reconnect
调用最多connect
六次,每次connect
调用在失败时reconnect
,一直循环直到无法正常工作的连接配置以某种方式神奇地开始工作(或者更有可能,直到您炸毁堆栈并崩溃)。
老实说,我建议简单地扔掉所有这些:只需调用lockConnection
(如果您使用 vibe.d)或new Connection(...)
(如果您不使用 vibe.d)并完成它。 如果您的连接设置错误,则再次尝试相同的连接设置不会修复它们。
lockConnection——是否应该有一个匹配的“解锁”? — 里克·詹姆斯
不,有问题的连接池来自vibe.d 。 当锁定连接的光纤退出时(通常意味着“当您的服务器完成处理请求时”),光纤锁定的任何连接都会自动返回到池中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.