Retry initial db connection, with adjustable option

This commit is contained in:
Daniel García
2020-10-03 22:31:52 +02:00
parent 22b9c80007
commit 729c9cff41
5 changed files with 49 additions and 12 deletions

View File

@ -410,7 +410,7 @@ fn _process_key(key: &str) -> String {
// Retry methods
//
pub fn retry<F, T, E>(func: F, max_tries: i32) -> Result<T, E>
pub fn retry<F, T, E>(func: F, max_tries: u32) -> Result<T, E>
where
F: Fn() -> Result<T, E>,
{
@ -432,3 +432,29 @@ where
}
}
}
pub fn retry_db<F, T, E>(func: F, max_tries: u32) -> Result<T, E>
where
F: Fn() -> Result<T, E>,
E: std::error::Error,
{
use std::{thread::sleep, time::Duration};
let mut tries = 0;
loop {
match func() {
ok @ Ok(_) => return ok,
Err(e) => {
tries += 1;
if tries >= max_tries && max_tries > 0 {
return Err(e);
}
warn!("Can't connect to database, retrying: {:?}", e);
sleep(Duration::from_millis(1_000));
}
}
}
}