1use anyhow::{anyhow, Result};
2use redis::Client;
3use serde::Deserialize;
4use std::sync::OnceLock;
5
6#[derive(Debug, Deserialize)]
7pub struct RedisConfig {
8 pub url: String,
9}
10
11static REDIS_POOL: OnceLock<bb8::Pool<Client>> = OnceLock::new();
12
13pub async fn init(config: &RedisConfig) -> Result<()> {
14 let client = Client::open(config.url.as_str())?;
15 let pool = bb8::Pool::builder().build(client).await?;
16 REDIS_POOL
17 .set(pool)
18 .map_err(|_| anyhow!("Failed to set OnceLock<RedisPool>"))
19}
20
21pub async fn conn() -> Result<bb8::PooledConnection<'static, Client>> {
22 Ok(REDIS_POOL
23 .get()
24 .ok_or_else(|| anyhow!("OnceLock<RedisPool> not initialized"))?
25 .get()
26 .await?)
27}