1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
use std::cmp::min;
use std::time::Duration;
use async_amqp::LapinAsyncStdExt;
use async_std::sync::RwLock;
use async_std::task::{block_on, sleep};
use lapin::{Connection, ConnectionProperties};
use log::info;
use icee_container_rs::set;
use crate::config::CONFIG;
pub struct RabbitMq {
conn: RwLock<Connection>,
}
pub fn init() {
block_on(set("rabbitmq", RabbitMq::new()));
}
impl RabbitMq {
#![allow(clippy::new_without_default)]
pub fn new() -> Self {
let conn = block_on(get_connection());
RabbitMq {
conn: RwLock::new(conn),
}
}
pub fn connection(&self) -> &RwLock<Connection> {
block_on(self.reconnect());
&self.conn
}
async fn reconnect(&self) {
let mut conn = self.conn.write().await;
if !conn.status().connected() {
*conn = get_connection().await;
}
}
}
async fn get_connection() -> Connection {
let mut timer = 2;
let max_timer = 30;
let addr = &CONFIG.rabbitmq.dsn;
loop {
info!("Connecting to rabbitmq: [{}]...", addr);
if let Ok(conn) =
Connection::connect(addr, ConnectionProperties::default().with_async_std()).await
{
info!("Connected");
return conn;
}
info!("Retry in {} seconds", timer);
sleep(Duration::from_secs(timer)).await;
timer = min(timer + 2, max_timer);
}
}