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