0
通过我的java代码我连接到多个数据库使用连接pooling.if我的数据库下降我需要处理重试逻辑来获取连接,直到它返回一个连接对象。重试逻辑uptil数据库出现
通过我的java代码我连接到多个数据库使用连接pooling.if我的数据库下降我需要处理重试逻辑来获取连接,直到它返回一个连接对象。重试逻辑uptil数据库出现
如果你的数据库连接抛出某种异常,那么你可以睡一会儿再重试该操作。
在下面的工人的例子是一个对象,做了一些工作,如连接到数据库,等等。这是非常通用的,所以您可以重试任何类型的操作,例如从文件中读取等
请注意,捕获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
你试过什么吗? – Gopi 2010-07-27 11:21:43
你需要提供更多的数据。你在使用什么技术?通过JDBC或像JPA,Hibernate,JDO等ORM的数据库访问? 你在使用什么连接池库?你用春天吗?等等 – 2010-07-27 12:31:31