admin_config/
redis_config.rs

1//! Redis 配置模块
2//!
3//! 提供 Redis 缓存数据库的连接配置
4
5use serde::{Deserialize, Serialize};
6
7/// Redis 配置
8///
9/// 用于配置 Redis 连接信息和连接池
10///
11/// # 示例
12///
13/// ```rust
14/// use admin_config::RedisConfig;
15///
16/// let config = RedisConfig::default();
17/// assert_eq!(config.port, 6379);
18/// assert_eq!(config.database, 0);
19///
20/// let conn_str = config.connection_string();
21/// assert!(conn_str.starts_with("redis://"));
22/// ```
23#[derive(Debug, Clone, Serialize, Deserialize)]
24pub struct RedisConfig {
25    /// 主机地址
26    pub host: String,
27    /// 端口
28    pub port: u16,
29    /// 用户名
30    pub username: Option<String>,
31    /// 密码
32    pub password: Option<String>,
33    /// 数据库索引
34    pub database: u8,
35    /// 最大连接池大小
36    pub max_pool_size: u32,
37    /// 连接超时时间(秒)
38    pub connect_timeout: u64,
39}
40
41impl Default for RedisConfig {
42    fn default() -> Self {
43        Self {
44            host: "localhost".to_string(),
45            port: 6379,
46            username: Some("".to_string()),
47            password: Some("".to_string()),
48            database: 0,
49            max_pool_size: 20,
50            connect_timeout: 5,
51        }
52    }
53}
54
55impl RedisConfig {
56    /// 生成 Redis 连接字符串
57    ///
58    /// 根据是否配置用户名和密码,生成相应格式的连接字符串
59    pub fn connection_string(&self) -> String {
60        match (&self.username, &self.password) {
61            (Some(username), Some(password)) => {
62                format!(
63                    "redis://{}:{}@{}:{}/{}",
64                    username, password, self.host, self.port, self.database
65                )
66            }
67            (None, Some(password)) => {
68                format!("redis://:{}@{}:{}/{}", password, self.host, self.port, self.database)
69            }
70            _ => {
71                format!("redis://{}:{}/{}", self.host, self.port, self.database)
72            }
73        }
74    }
75}