Files
web-rust-template-project/src/config/redis.rs
2026-02-13 15:57:29 +08:00

53 lines
1.2 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
use serde::Deserialize;
#[derive(Debug, Deserialize, Clone)]
pub struct RedisConfig {
/// Redis 主机地址
#[serde(default = "default_redis_host")]
pub host: String,
/// Redis 端口
#[serde(default = "default_redis_port")]
pub port: u16,
/// Redis 密码(可选)
#[serde(default)]
pub password: Option<String>,
/// Redis 数据库编号(可选)
#[serde(default = "default_redis_db")]
pub db: u8,
}
pub fn default_redis_host() -> String {
"localhost".to_string()
}
pub fn default_redis_port() -> u16 {
6379
}
pub fn default_redis_db() -> u8 {
0
}
impl RedisConfig {
/// 构建 Redis 连接 URL
pub fn build_url(&self) -> String {
// 判断密码是否存在且非空
match &self.password {
Some(password) if !password.is_empty() => {
// 有密码redis://:password@host:port/db
format!(
"redis://:{}@{}:{}/{}",
password, self.host, self.port, self.db
)
}
_ => {
// 无密码None 或空字符串redis://host:port/db
format!("redis://{}:{}/{}", self.host, self.port, self.db)
}
}
}
}