通过我的java代码我使用连接池连接到多个数据库。如果我的数据库出现故障,我需要处理重试逻辑以获得连接,直到它返回一个连接对象。
答案 0 :(得分:0)
如果您的数据库连接抛出某种异常,那么您可以稍微休眠一下并再次重试该操作。
在下面的示例中,worker是一个执行某些工作的对象,例如连接到db等。它非常通用,因此您可以重试任何类型的操作,例如从文件读取等。
请注意,抓住Throwable
可能不一定是个好主意。
boolean success = false;
int i = 0;
long delay = retryDelay;
LOGGER.info("Starting operation");
/*
* Loop until you cannot retry anymore or the operation completed successfully
* The catch block has a nested try catch to ensure that nothing goes wrong
* while trying to sleep
*
* In case of failure the last retry exception is propagated up to the calling
* class.
*/
while (i++ < retryMax && !success)
{
try
{
worker.work();
success = true;
}
catch (Throwable t)
{
try
{
LOGGER.warn("Caught throwable", t);
if (i == retryMax)
{
LOGGER.warn("Retry maximum reached, propagating error");
throw t;
}
if (retryPolicy == RetryPolicy.ESCALATING)
{
delay *= 2;
}
LOGGER.info("Sleeping for " + delay + " milliseconds");
Thread.sleep(delay);
}
catch (Throwable tt)
{
/*
* Quick check to see if the maximum has been hit, so we don't log twice
*
* t is the original error, and tt is the error we got while retrying
* tt would most likely be a InterruptedException or something
*/
if (i == retryMax)
{
throw t;
}
LOGGER.warn("Error while retrying, propagating original error up", tt);
throw t;
}
}
} // end retry loop