pub struct GlobalRedis;Expand description
全局 Redis 访问器
封装 yang-db::RedisClient,提供全局静态访问接口。 所有 Redis 操作都通过 yang-db 库实现。
Implementations§
Source§impl GlobalRedis
impl GlobalRedis
Sourcepub async fn init(url: &str, config: RedisConfig) -> Result<(), BaseError>
pub async fn init(url: &str, config: RedisConfig) -> Result<(), BaseError>
初始化全局 Redis
§参数
url: Redis 连接字符串,格式:redis://host:port或redis://:password@host:portconfig: Redis 配置,包含连接池参数
§返回
Ok(()): 初始化成功Err(BaseError): 初始化失败
§错误
RedisConnectionFailed: Redis 连接失败RedisAlreadyInitialized: Redis 已经初始化
§示例
use yang_base::database::GlobalRedis;
use yang_db::redis::RedisConfig;
let config = RedisConfig::default()
.with_max_connections(10)
.with_connect_timeout(5)
.with_wait_timeout(30)
.with_idle_timeout(300)
.with_enable_logging(true);
GlobalRedis::init("redis://127.0.0.1:6379", config).await?;Sourcepub fn client() -> Result<&'static RedisClient, BaseError>
pub fn client() -> Result<&'static RedisClient, BaseError>
获取全局 Redis 实例
§返回
Ok(&'static RedisClient): yang-db::RedisClient 实例的静态引用Err(BaseError): Redis 未初始化
§错误
RedisNotInitialized: Redis 未初始化,需要先调用init方法
§API 一致性说明 (A-M4)
本方法名为 client(),而数据库对等方法名为
GlobalDatabase::get()。
这是历史命名不对称,未来应统一为同一种命名风格(例如都叫 get() 或都叫
client())。
Sourcepub async fn health_check() -> Result<bool, BaseError>
pub async fn health_check() -> Result<bool, BaseError>
Redis 健康检查
委托底层 RedisClient::health_check,通过 PING 命令验证连接可达性。
§返回
Ok(true): Redis 连接正常Ok(false): PING 响应异常Err(BaseError): Redis 未初始化或无法获取连接
§错误
BaseError::RedisNotInitialized: Redis 未初始化,需要先调用init方法BaseError::RedisOperationFailed: 无法获取连接
Sourcepub fn pool_status() -> Result<PoolStatus, BaseError>
pub fn pool_status() -> Result<PoolStatus, BaseError>
获取 Redis 连接池状态
委托底层 RedisClient::pool_status,返回连接池的实时统计信息。
§返回
Ok(PoolStatus): 连接池状态(含max_size/size/available/waiting)Err(BaseError): Redis 未初始化
§错误
BaseError::RedisNotInitialized: Redis 未初始化,需要先调用init方法
Sourcepub async fn close()
pub async fn close()
优雅关闭全局 Redis 连接池(I3)。
供编排式停机(crate::lifecycle)调用。OnceLock 单例不重置,仅原地关闭
连接池——停机后不应再使用。未初始化时为 no-op。
Sourcepub async fn set(
key: impl Into<String>,
value: impl Into<String>,
expire_seconds: Option<i64>,
) -> Result<(), BaseError>
pub async fn set( key: impl Into<String>, value: impl Into<String>, expire_seconds: Option<i64>, ) -> Result<(), BaseError>
设置字符串值
§参数
key: 键名value: 值expire_seconds: 过期时间(秒),None 表示不过期。秒数必须为正;Some(0)或Some(负数)会被 Redis 拒绝并返回BaseError::RedisOperationFailed
§返回
Ok(()): 设置成功Err(BaseError): 设置失败
§错误
BaseError::RedisNotInitialized: Redis 未初始化,需要先调用init方法BaseError::RedisOperationFailed: Redis 命令执行失败
Sourcepub async fn set_nx_ex(
key: impl Into<String>,
value: impl Into<String>,
ttl: i64,
) -> Result<bool, BaseError>
pub async fn set_nx_ex( key: impl Into<String>, value: impl Into<String>, ttl: i64, ) -> Result<bool, BaseError>
仅当键不存在时设置值并指定过期时间(原子 SET NX EX)。
委托 RedisClient::set_nx_ex,是原子性的“不存在则写入+设过期时间“操作。
适用于分布式锁、去重、以及需要竞态保护的场景(如 Refresh Token 轮换)。
§参数
key: 键名value: 值ttl: 过期时间(秒),必须为正数
§返回
Ok(true): 设置成功(键之前不存在,本调用是首次写入)Ok(false): 键已存在,未设置Err(BaseError): 操作失败
§错误
BaseError::RedisNotInitialized: Redis 未初始化,需要先调用init方法BaseError::RedisOperationFailed: Redis 命令执行失败
Sourcepub async fn hset(
key: impl Into<String>,
field: impl Into<String>,
value: impl Into<String>,
) -> Result<bool, BaseError>
pub async fn hset( key: impl Into<String>, field: impl Into<String>, value: impl Into<String>, ) -> Result<bool, BaseError>
Sourcepub async fn hget(
key: impl Into<String>,
field: impl Into<String>,
) -> Result<Option<String>, BaseError>
pub async fn hget( key: impl Into<String>, field: impl Into<String>, ) -> Result<Option<String>, BaseError>
Sourcepub async fn hdel(
key: impl Into<String>,
fields: &[impl AsRef<str>],
) -> Result<i64, BaseError>
pub async fn hdel( key: impl Into<String>, fields: &[impl AsRef<str>], ) -> Result<i64, BaseError>
Sourcepub async fn hexists(
key: impl Into<String>,
field: impl Into<String>,
) -> Result<bool, BaseError>
pub async fn hexists( key: impl Into<String>, field: impl Into<String>, ) -> Result<bool, BaseError>
Sourcepub async fn lpush(
key: impl Into<String>,
values: &[impl AsRef<str>],
) -> Result<i64, BaseError>
pub async fn lpush( key: impl Into<String>, values: &[impl AsRef<str>], ) -> Result<i64, BaseError>
Sourcepub async fn rpush(
key: impl Into<String>,
values: &[impl AsRef<str>],
) -> Result<i64, BaseError>
pub async fn rpush( key: impl Into<String>, values: &[impl AsRef<str>], ) -> Result<i64, BaseError>
Sourcepub async fn lrange(
key: impl Into<String>,
start: i64,
stop: i64,
) -> Result<Vec<String>, BaseError>
pub async fn lrange( key: impl Into<String>, start: i64, stop: i64, ) -> Result<Vec<String>, BaseError>
Sourcepub async fn sadd(
key: impl Into<String>,
members: &[impl AsRef<str>],
) -> Result<i64, BaseError>
pub async fn sadd( key: impl Into<String>, members: &[impl AsRef<str>], ) -> Result<i64, BaseError>
Sourcepub async fn srem(
key: impl Into<String>,
members: &[impl AsRef<str>],
) -> Result<i64, BaseError>
pub async fn srem( key: impl Into<String>, members: &[impl AsRef<str>], ) -> Result<i64, BaseError>
Sourcepub async fn sismember(
key: impl Into<String>,
member: impl Into<String>,
) -> Result<bool, BaseError>
pub async fn sismember( key: impl Into<String>, member: impl Into<String>, ) -> Result<bool, BaseError>
Sourcepub async fn zadd(
key: impl Into<String>,
members: &[(f64, String)],
) -> Result<i64, BaseError>
pub async fn zadd( key: impl Into<String>, members: &[(f64, String)], ) -> Result<i64, BaseError>
Sourcepub async fn zrem(
key: impl Into<String>,
members: &[impl AsRef<str>],
) -> Result<i64, BaseError>
pub async fn zrem( key: impl Into<String>, members: &[impl AsRef<str>], ) -> Result<i64, BaseError>
Sourcepub async fn zrange(
key: impl Into<String>,
start: i64,
stop: i64,
) -> Result<Vec<String>, BaseError>
pub async fn zrange( key: impl Into<String>, start: i64, stop: i64, ) -> Result<Vec<String>, BaseError>
Sourcepub async fn hincrby(
key: impl Into<String>,
field: impl Into<String>,
increment: i64,
) -> Result<i64, BaseError>
pub async fn hincrby( key: impl Into<String>, field: impl Into<String>, increment: i64, ) -> Result<i64, BaseError>
Sourcepub async fn hincrbyfloat(
key: impl Into<String>,
field: impl Into<String>,
increment: f64,
) -> Result<f64, BaseError>
pub async fn hincrbyfloat( key: impl Into<String>, field: impl Into<String>, increment: f64, ) -> Result<f64, BaseError>
Sourcepub async fn zrange_with_scores(
key: impl Into<String>,
start: i64,
stop: i64,
) -> Result<Vec<(String, f64)>, BaseError>
pub async fn zrange_with_scores( key: impl Into<String>, start: i64, stop: i64, ) -> Result<Vec<(String, f64)>, BaseError>
Sourcepub async fn zrevrange(
key: impl Into<String>,
start: i64,
stop: i64,
) -> Result<Vec<String>, BaseError>
pub async fn zrevrange( key: impl Into<String>, start: i64, stop: i64, ) -> Result<Vec<String>, BaseError>
Sourcepub async fn zincrby(
key: impl Into<String>,
increment: f64,
member: impl Into<String>,
) -> Result<f64, BaseError>
pub async fn zincrby( key: impl Into<String>, increment: f64, member: impl Into<String>, ) -> Result<f64, BaseError>
Sourcepub fn transaction() -> Result<RedisTransaction, BaseError>
pub fn transaction() -> Result<RedisTransaction, BaseError>
获取 Redis 事务对象
返回 yang_db::redis::RedisTransaction,支持 WATCH/MULTI/EXEC 乐观锁事务。
§返回
Ok(RedisTransaction): 事务对象Err(BaseError): Redis 未初始化
§说明
事务支持链式调用,可在事务中执行多个命令。
如需使用 Pipeline 批量操作,可通过 GlobalRedis::client()?.pipeline() 获取。
如需执行 Lua 脚本,可通过 GlobalRedis::client()?.script(code) 创建脚本对象。
§示例
// 基础事务
let mut tx = GlobalRedis::transaction()?;
tx.set("key1", "value1")
.set("key2", "value2")
.incr("counter");
let results: (String, String, i64) = tx.exec().await?;
// 乐观锁事务
let mut tx = GlobalRedis::transaction()?;
tx.watch(&["balance".to_string()]);
tx.set("balance", "900");
let result: (String,) = tx.exec().await?;
// Pipeline 批量操作
let mut pipeline = GlobalRedis::client()?.pipeline();
pipeline.set("k1", "v1").set("k2", "v2");
let results = pipeline.execute().await?;Auto Trait Implementations§
impl Freeze for GlobalRedis
impl RefUnwindSafe for GlobalRedis
impl Send for GlobalRedis
impl Sync for GlobalRedis
impl Unpin for GlobalRedis
impl UnsafeUnpin for GlobalRedis
impl UnwindSafe for GlobalRedis
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
Source§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self>
fn into_either(self, into_left: bool) -> Either<Self, Self>
self into a Left variant of Either<Self, Self>
if into_left is true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
self into a Left variant of Either<Self, Self>
if into_left(&self) returns true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read more