Files
appks/config/redis.rs
T
2026-06-07 11:30:56 +08:00

88 lines
2.7 KiB
Rust

use crate::config::AppConfig;
use crate::error::{AppError, AppResult};
impl AppConfig {
pub fn redis_url(&self) -> AppResult<Option<String>> {
self.get_env::<String>("APP_REDIS_URL")
}
pub fn redis_cluster_enabled(&self) -> AppResult<bool> {
self.get_env_or("APP_REDIS_CLUSTER_ENABLED", false)
}
pub fn redis_cluster_nodes(&self) -> AppResult<Vec<String>> {
match self.get_env::<String>("APP_REDIS_CLUSTER_NODES")? {
Some(s) if !s.is_empty() => Ok(s
.split(',')
.map(|u| u.trim().to_string())
.filter(|u| !u.is_empty())
.collect()),
_ => Ok(Vec::new()),
}
}
pub fn redis_read_from_replicas(&self) -> AppResult<bool> {
self.get_env_or("APP_REDIS_READ_FROM_REPLICAS", false)
}
pub fn redis_username(&self) -> AppResult<Option<String>> {
self.get_env::<String>("APP_REDIS_USERNAME")
}
pub fn redis_password(&self) -> AppResult<Option<String>> {
self.get_env::<String>("APP_REDIS_PASSWORD")
}
pub fn redis_database(&self) -> AppResult<u8> {
self.get_env_or("APP_REDIS_DATABASE", 0u8)
}
pub fn redis_max_connections(&self) -> AppResult<u32> {
self.get_env_or("APP_REDIS_MAX_CONNECTIONS", 20)
}
pub fn redis_min_connections(&self) -> AppResult<u32> {
self.get_env_or("APP_REDIS_MIN_CONNECTIONS", 2)
}
pub fn redis_idle_timeout(&self) -> AppResult<u64> {
self.get_env_or("APP_REDIS_IDLE_TIMEOUT", 300)
}
pub fn redis_connection_timeout(&self) -> AppResult<u64> {
self.get_env_or("APP_REDIS_CONNECTION_TIMEOUT", 5)
}
pub fn redis_max_retries(&self) -> AppResult<u32> {
self.get_env_or("APP_REDIS_MAX_RETRIES", 3)
}
pub fn redis_retry_delay_ms(&self) -> AppResult<u64> {
self.get_env_or("APP_REDIS_RETRY_DELAY_MS", 100)
}
pub fn redis_tls_enabled(&self) -> AppResult<bool> {
self.get_env_or("APP_REDIS_TLS_ENABLED", false)
}
pub fn redis_key_prefix(&self) -> AppResult<String> {
self.get_env_or("APP_REDIS_KEY_PREFIX", "".to_string())
}
pub fn redis_validate(&self) -> AppResult<()> {
if self.redis_cluster_enabled()? {
let nodes = self.redis_cluster_nodes()?;
if nodes.is_empty() {
return Err(AppError::Config(
"Redis cluster enabled but APP_REDIS_CLUSTER_NODES is empty".into(),
));
}
} else if self.redis_url()?.is_none() {
return Err(AppError::Config(
"Redis cluster disabled but APP_REDIS_URL is not set".into(),
));
}
Ok(())
}
}