Skip to main content

RedisClient

Struct RedisClient 

Source
pub struct RedisClient { /* private fields */ }
Expand description

Redis 客户端

提供 Redis 数据库操作的统一接口,支持连接池管理

Implementations§

Source§

impl RedisClient

Source

pub async fn connect(url: impl Into<String>) -> Result<Self>

连接到 Redis 服务器

§参数
  • url: Redis 连接 URL,格式为 redis://host:portredis://host:port/db
§返回
  • Ok(RedisClient): 连接成功
  • Err(DbError): 连接失败
§示例
use yang_db::RedisClient;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = RedisClient::connect("redis://127.0.0.1:6379").await?;
    Ok(())
}
Source

pub async fn connect_with_config( url: impl Into<String>, config: RedisConfig, ) -> Result<Self>

使用自定义配置连接到 Redis 服务器

§参数
  • url: Redis 连接 URL
  • config: Redis 配置
§返回
  • Ok(RedisClient): 连接成功
  • Err(DbError): 连接失败
§示例
use yang_db::{RedisClient, RedisConfig};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let config = RedisConfig::new(20, 10, 15, true);
    let client = RedisClient::connect_with_config("redis://127.0.0.1:6379", config).await?;
    Ok(())
}
Source

pub fn pool(&self) -> &Pool

获取连接池引用

§返回

连接池的引用

Source

pub fn pipeline(&self) -> RedisPipeline

创建 Pipeline 批量操作

Pipeline 允许将多个命令打包发送到 Redis 服务器,减少网络往返次数,提高性能。

§返回

新的 Pipeline 实例

§示例
use yang_db::RedisClient;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = RedisClient::connect("redis://127.0.0.1:6379").await?;
     
    let mut pipeline = client.pipeline();
    pipeline.set("key1", "value1")
            .set("key2", "value2")
            .get("key1")
            .incr("counter");

    let results = pipeline.execute().await?;
    println!("Pipeline 执行结果: {:?}", results);
     
    Ok(())
}
Source

pub fn transaction(&self) -> RedisTransaction

创建 Redis 事务

使用 WATCH/MULTI/EXEC 机制实现乐观锁事务。事务会自动处理 WATCH 冲突并重试。

§返回

新的事务实例

§示例:基础事务
use yang_db::RedisClient;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = RedisClient::connect("redis://127.0.0.1:6379").await?;
     
    let mut tx = client.transaction();
    tx.set("key1", "value1")
      .set("key2", "value2")
      .incr("counter");
     
    let results: (String, String, i64) = tx.exec().await?;
    println!("事务执行结果: {:?}", results);
     
    Ok(())
}
§示例:乐观锁实现余额扣减
use yang_db::RedisClient;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = RedisClient::connect("redis://127.0.0.1:6379").await?;
     
    // 初始化余额
    client.set("balance", "1000").await?;
     
    // 读取当前余额
    let balance_str = client.get("balance").await?.unwrap();
    let balance: i64 = balance_str.parse().unwrap();
     
    // 使用事务扣减余额
    if balance >= 100 {
        let mut tx = client.transaction();
        tx.watch(&["balance".to_string()]);
        tx.set("balance", (balance - 100).to_string());
         
        let result: (String,) = tx.exec().await?;
        println!("余额扣减成功: {:?}", result);
    }
     
    Ok(())
}
Source

pub async fn execute(&self, cmd: &Cmd) -> Result<RedisValue>

执行 Redis 命令

§参数
  • cmd: Redis 命令
§返回
  • Ok(RedisValue): 命令执行成功
  • Err(DbError): 命令执行失败
§示例
use yang_db::RedisClient;
use redis::cmd;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = RedisClient::connect("redis://127.0.0.1:6379").await?;
     
    let mut cmd = cmd("SET");
    cmd.arg("key").arg("value");
    let result = client.execute(&cmd).await?;
     
    Ok(())
}
Source

pub async fn set( &self, key: impl Into<String>, value: impl Into<String>, ) -> Result<()>

SET - 设置键值

§参数
  • key: 键
  • value: 值
§返回
  • Ok(()): 设置成功
  • Err(DbError): 设置失败
Source

pub async fn get(&self, key: impl Into<String>) -> Result<Option<String>>

GET - 获取键的值

§参数
  • key: 键
§返回
  • Ok(Some(String)): 键存在,返回值
  • Ok(None): 键不存在
  • Err(DbError): 获取失败
Source

pub async fn setex( &self, key: impl Into<String>, seconds: i64, value: impl Into<String>, ) -> Result<()>

SETEX - 设置键值并指定过期时间(秒)

§参数
  • key: 键
  • seconds: 过期时间(秒)
  • value: 值
Source

pub async fn setnx( &self, key: impl Into<String>, value: impl Into<String>, ) -> Result<bool>

SETNX - 仅当键不存在时设置值

§返回
  • Ok(true): 设置成功
  • Ok(false): 键已存在,未设置
Source

pub async fn getset( &self, key: impl Into<String>, value: impl Into<String>, ) -> Result<Option<String>>

GETSET - 设置新值并返回旧值

§返回
  • Ok(Some(String)): 返回旧值
  • Ok(None): 键不存在
Source

pub async fn mget(&self, keys: &[String]) -> Result<Vec<Option<String>>>

MGET - 批量获取多个键的值

§返回

返回值数组,不存在的键返回 None

Source

pub async fn mset(&self, pairs: &[(String, String)]) -> Result<()>

MSET - 批量设置多个键值对

§参数
  • pairs: 键值对数组
Source

pub async fn incr(&self, key: impl Into<String>) -> Result<i64>

INCR - 将键的值增加 1

§返回

返回增加后的值

Source

pub async fn incrby( &self, key: impl Into<String>, increment: i64, ) -> Result<i64>

INCRBY - 将键的值增加指定数量

§返回

返回增加后的值

Source

pub async fn decr(&self, key: impl Into<String>) -> Result<i64>

DECR - 将键的值减少 1

§返回

返回减少后的值

Source

pub async fn decrby( &self, key: impl Into<String>, decrement: i64, ) -> Result<i64>

DECRBY - 将键的值减少指定数量

§返回

返回减少后的值

Source

pub async fn append( &self, key: impl Into<String>, value: impl Into<String>, ) -> Result<i64>

APPEND - 将值追加到键的原值末尾

§返回

返回追加后字符串的长度

Source

pub async fn strlen(&self, key: impl Into<String>) -> Result<i64>

STRLEN - 获取键存储的字符串长度

§返回

返回字符串长度,键不存在返回 0

Source

pub async fn getrange( &self, key: impl Into<String>, start: i64, end: i64, ) -> Result<String>

GETRANGE - 获取字符串的子串

§参数
  • key: 键
  • start: 起始偏移量(0 表示第一个字符,-1 表示最后一个字符)
  • end: 结束偏移量(包含)
§返回
  • Ok(String): 子串内容
§示例
use yang_db::RedisClient;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = RedisClient::connect("redis://127.0.0.1:6379").await?;
     
    // 假设 key "mykey" 的值是 "Hello World"
    client.set("mykey", "Hello World").await?;
    let substr = client.getrange("mykey", 0, 4).await?;  // "Hello"
    let substr2 = client.getrange("mykey", -5, -1).await?; // "World"
     
    Ok(())
}
Source

pub async fn setrange( &self, key: impl Into<String>, offset: i64, value: impl Into<String>, ) -> Result<i64>

SETRANGE - 从指定偏移量开始替换字符串内容

§参数
  • key: 键
  • offset: 起始偏移量
  • value: 要设置的值
§返回
  • Ok(i64): 修改后字符串的长度
§示例
use yang_db::RedisClient;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = RedisClient::connect("redis://127.0.0.1:6379").await?;
     
    client.set("mykey", "Hello World").await?;
    let len = client.setrange("mykey", 6, "Redis").await?; // "Hello Redis"
     
    Ok(())
}
Source

pub async fn incrbyfloat( &self, key: impl Into<String>, increment: f64, ) -> Result<f64>

INCRBYFLOAT - 将键的浮点数值增加指定数量

§参数
  • key: 键
  • increment: 增量(可以是负数)
§返回
  • Ok(f64): 增加后的值
§示例
use yang_db::RedisClient;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = RedisClient::connect("redis://127.0.0.1:6379").await?;
     
    client.set("price", "10.5").await?;
    let new_price = client.incrbyfloat("price", 2.3).await?; // 12.8
     
    Ok(())
}
Source

pub async fn psetex( &self, key: impl Into<String>, milliseconds: i64, value: impl Into<String>, ) -> Result<()>

PSETEX - 设置键值并指定毫秒级过期时间

§参数
  • key: 键
  • milliseconds: 过期时间(毫秒)
  • value: 值
§示例
use yang_db::RedisClient;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = RedisClient::connect("redis://127.0.0.1:6379").await?;
     
    // 设置键值,100 毫秒后过期
    client.psetex("session", 100, "data").await?;
     
    Ok(())
}
Source

pub async fn hset( &self, key: impl Into<String>, field: impl Into<String>, value: impl Into<String>, ) -> Result<bool>

HSET - 设置哈希表字段的值

§返回
  • Ok(true): 新字段被设置
  • Ok(false): 字段已存在,值被更新
Source

pub async fn hget( &self, key: impl Into<String>, field: impl Into<String>, ) -> Result<Option<String>>

HGET - 获取哈希表字段的值

§返回
  • Ok(Some(String)): 字段存在
  • Ok(None): 字段不存在
Source

pub async fn hdel( &self, key: impl Into<String>, fields: &[String], ) -> Result<i64>

HDEL - 删除哈希表的一个或多个字段

§返回

返回被删除字段的数量

Source

pub async fn hexists( &self, key: impl Into<String>, field: impl Into<String>, ) -> Result<bool>

HEXISTS - 检查哈希表字段是否存在

§返回
  • Ok(true): 字段存在
  • Ok(false): 字段不存在
Source

pub async fn hmset( &self, key: impl Into<String>, fields: &[(String, String)], ) -> Result<()>

HMSET - 批量设置哈希表的多个字段

Source

pub async fn hmget( &self, key: impl Into<String>, fields: &[String], ) -> Result<Vec<Option<String>>>

HMGET - 批量获取哈希表的多个字段值

§返回

返回值数组,不存在的字段返回 None

Source

pub async fn hgetall( &self, key: impl Into<String>, ) -> Result<Vec<(String, String)>>

HGETALL - 获取哈希表的所有字段和值

§返回

返回字段-值对的向量

Source

pub async fn hlen(&self, key: impl Into<String>) -> Result<i64>

HLEN - 获取哈希表的字段数量

Source

pub async fn hkeys(&self, key: impl Into<String>) -> Result<Vec<String>>

HKEYS - 获取哈希表的所有字段名

Source

pub async fn hvals(&self, key: impl Into<String>) -> Result<Vec<String>>

HVALS - 获取哈希表的所有值

Source

pub async fn hincrby( &self, key: impl Into<String>, field: impl Into<String>, increment: i64, ) -> Result<i64>

HINCRBY - 将哈希表字段的整数值增加指定数量

Source

pub async fn hincrbyfloat( &self, key: impl Into<String>, field: impl Into<String>, increment: f64, ) -> Result<f64>

HINCRBYFLOAT - 将哈希表字段的浮点数值增加指定数量

Source

pub async fn lpush( &self, key: impl Into<String>, values: &[String], ) -> Result<i64>

LPUSH - 将一个或多个值插入列表头部

§返回

返回插入后列表的长度

Source

pub async fn rpush( &self, key: impl Into<String>, values: &[String], ) -> Result<i64>

RPUSH - 将一个或多个值插入列表尾部

§返回

返回插入后列表的长度

Source

pub async fn lpop(&self, key: impl Into<String>) -> Result<Option<String>>

LPOP - 移除并返回列表的头元素

§返回
  • Ok(Some(String)): 返回头元素
  • Ok(None): 列表为空
Source

pub async fn rpop(&self, key: impl Into<String>) -> Result<Option<String>>

RPOP - 移除并返回列表的尾元素

§返回
  • Ok(Some(String)): 返回尾元素
  • Ok(None): 列表为空
Source

pub async fn lrange( &self, key: impl Into<String>, start: i64, stop: i64, ) -> Result<Vec<String>>

LRANGE - 获取列表指定范围内的元素

§参数
  • start: 起始索引(0 表示第一个元素)
  • stop: 结束索引(-1 表示最后一个元素)
Source

pub async fn llen(&self, key: impl Into<String>) -> Result<i64>

LLEN - 获取列表长度

Source

pub async fn lindex( &self, key: impl Into<String>, index: i64, ) -> Result<Option<String>>

LINDEX - 获取列表指定索引的元素

§返回
  • Ok(Some(String)): 返回元素
  • Ok(None): 索引超出范围
Source

pub async fn lset( &self, key: impl Into<String>, index: i64, value: impl Into<String>, ) -> Result<()>

LSET - 设置列表指定索引的元素值

Source

pub async fn ltrim( &self, key: impl Into<String>, start: i64, stop: i64, ) -> Result<()>

LTRIM - 修剪列表,仅保留指定范围内的元素

Source

pub async fn linsert( &self, key: impl Into<String>, before_after: &str, pivot: impl Into<String>, value: impl Into<String>, ) -> Result<i64>

LINSERT - 在列表的指定元素前或后插入新元素

§参数
  • key: 键
  • before_after: “BEFORE” 或 “AFTER”
  • pivot: 参考元素
  • value: 要插入的值
§返回
  • Ok(i64): 插入后列表的长度,-1 表示 pivot 不存在
§示例
use yang_db::RedisClient;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = RedisClient::connect("redis://127.0.0.1:6379").await?;
     
    client.rpush("mylist", &["a".to_string(), "c".to_string()]).await?;
    client.linsert("mylist", "BEFORE", "c", "b").await?; // ["a", "b", "c"]
     
    Ok(())
}
Source

pub async fn lrem( &self, key: impl Into<String>, count: i64, value: impl Into<String>, ) -> Result<i64>

LREM - 删除列表中的指定元素

§参数
  • key: 键
  • count: 删除数量
    • count > 0: 从头到尾删除 count 个匹配元素
    • count < 0: 从尾到头删除 |count| 个匹配元素
    • count = 0: 删除所有匹配元素
  • value: 要删除的值
§返回
  • Ok(i64): 被删除元素的数量
§示例
use yang_db::RedisClient;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = RedisClient::connect("redis://127.0.0.1:6379").await?;
     
    client.rpush("mylist", &["a".to_string(), "b".to_string(), "a".to_string()]).await?;
    let removed = client.lrem("mylist", 2, "a").await?; // 删除 2 个 "a"
     
    Ok(())
}
Source

pub async fn rpoplpush( &self, source: impl Into<String>, destination: impl Into<String>, ) -> Result<Option<String>>

RPOPLPUSH - 从源列表尾部弹出元素并插入到目标列表头部

§参数
  • source: 源列表键
  • destination: 目标列表键
§返回
  • Ok(Some(String)): 被移动的元素
  • Ok(None): 源列表为空
§示例
use yang_db::RedisClient;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = RedisClient::connect("redis://127.0.0.1:6379").await?;
     
    client.rpush("list1", &["a".to_string(), "b".to_string()]).await?;
    let elem = client.rpoplpush("list1", "list2").await?; // "b"
     
    Ok(())
}
Source

pub async fn blpop( &self, keys: &[String], timeout: i64, ) -> Result<Option<(String, String)>>

BLPOP - 阻塞式地从列表头部弹出元素

§参数
  • keys: 键列表(按顺序检查)
  • timeout: 超时时间(秒),0 表示无限等待
§返回
  • Ok(Some((String, String))): (键名, 元素值)
  • Ok(None): 超时
§示例
use yang_db::RedisClient;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = RedisClient::connect("redis://127.0.0.1:6379").await?;
     
    let result = client.blpop(&["queue1".to_string(), "queue2".to_string()], 5).await?;
    if let Some((key, value)) = result {
        println!("从 {} 弹出: {}", key, value);
    }
     
    Ok(())
}
Source

pub async fn brpop( &self, keys: &[String], timeout: i64, ) -> Result<Option<(String, String)>>

BRPOP - 阻塞式地从列表尾部弹出元素

§参数
  • keys: 键列表(按顺序检查)
  • timeout: 超时时间(秒),0 表示无限等待
§返回
  • Ok(Some((String, String))): (键名, 元素值)
  • Ok(None): 超时
§示例
use yang_db::RedisClient;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = RedisClient::connect("redis://127.0.0.1:6379").await?;
     
    let result = client.brpop(&["queue1".to_string()], 10).await?;
     
    Ok(())
}
Source

pub async fn sadd( &self, key: impl Into<String>, members: &[String], ) -> Result<i64>

SADD - 向集合添加一个或多个成员

§返回

返回被添加到集合中的新元素数量

Source

pub async fn srem( &self, key: impl Into<String>, members: &[String], ) -> Result<i64>

SREM - 移除集合中的一个或多个成员

§返回

返回被移除的元素数量

Source

pub async fn smembers(&self, key: impl Into<String>) -> Result<Vec<String>>

SMEMBERS - 获取集合的所有成员

Source

pub async fn sismember( &self, key: impl Into<String>, member: impl Into<String>, ) -> Result<bool>

SISMEMBER - 检查元素是否是集合的成员

§返回
  • Ok(true): 元素是集合成员
  • Ok(false): 元素不是集合成员
Source

pub async fn scard(&self, key: impl Into<String>) -> Result<i64>

SCARD - 获取集合的成员数量

Source

pub async fn spop(&self, key: impl Into<String>) -> Result<Option<String>>

SPOP - 移除并返回集合中的一个随机元素

§返回
  • Ok(Some(String)): 返回被移除的元素
  • Ok(None): 集合为空
Source

pub async fn srandmember( &self, key: impl Into<String>, ) -> Result<Option<String>>

SRANDMEMBER - 返回集合中的一个随机元素(不移除)

§返回
  • Ok(Some(String)): 返回随机元素
  • Ok(None): 集合为空
Source

pub async fn sinter(&self, keys: &[String]) -> Result<Vec<String>>

SINTER - 返回多个集合的交集

计算所有给定集合的共同成员。

§参数
  • keys: 参与交集运算的集合键列表
§返回

所有集合中都存在的成员列表

§示例
let common = client.sinter(&["set_a".to_string(), "set_b".to_string()]).await?;
Source

pub async fn sunion(&self, keys: &[String]) -> Result<Vec<String>>

SUNION - 返回多个集合的并集

计算所有给定集合的所有成员。

§参数
  • keys: 参与并集运算的集合键列表
§返回

所有集合的成员合并列表(去重)

Source

pub async fn sdiff(&self, keys: &[String]) -> Result<Vec<String>>

SDIFF - 返回多个集合的差集

计算第一个集合与其余集合的差集(仅存在于第一个集合中的成员)。

§参数
  • keys: 集合键列表,第一个为基准集合
§返回

仅存在于第一个集合中的成员列表

Source

pub async fn smove( &self, source: impl Into<String>, destination: impl Into<String>, member: impl Into<String>, ) -> Result<bool>

SMOVE - 将指定成员从源集合移动到目标集合

§参数
  • source: 源集合键
  • destination: 目标集合键
  • member: 要移动的成员
§返回
  • Ok(true): 移动成功
  • Ok(false): 成员不存在于源集合
Source

pub async fn sscan( &self, key: impl Into<String>, cursor: i64, pattern: Option<&str>, count: Option<i64>, ) -> Result<(i64, Vec<String>)>

SSCAN - 增量式迭代集合中的元素

§参数
  • key: 集合键
  • cursor: 游标(初始传 0)
  • pattern: 可选的匹配模式
  • count: 可选的每批返回数量提示
§返回
  • Ok((i64, Vec<String>)): (下一游标, 本批成员列表)
Source

pub async fn zadd( &self, key: impl Into<String>, members: &[(f64, String)], ) -> Result<i64>

ZADD - 向有序集合添加一个或多个成员

§返回

返回被添加的新成员数量

Source

pub async fn zrem( &self, key: impl Into<String>, members: &[String], ) -> Result<i64>

ZREM - 移除有序集合中的一个或多个成员

§返回

返回被移除的成员数量

Source

pub async fn zscore( &self, key: impl Into<String>, member: impl Into<String>, ) -> Result<Option<f64>>

ZSCORE - 获取成员的分数

§返回
  • Ok(Some(f64)): 返回分数
  • Ok(None): 成员不存在
Source

pub async fn zcard(&self, key: impl Into<String>) -> Result<i64>

ZCARD - 获取有序集合的成员数量

Source

pub async fn zrange( &self, key: impl Into<String>, start: i64, stop: i64, ) -> Result<Vec<String>>

ZRANGE - 按索引范围获取有序集合的成员

§参数
  • start: 起始索引
  • stop: 结束索引
Source

pub async fn zrangebyscore( &self, key: impl Into<String>, min: f64, max: f64, ) -> Result<Vec<String>>

ZRANGEBYSCORE - 按分数范围获取有序集合的成员

§参数
  • min: 最小分数
  • max: 最大分数
Source

pub async fn zcount( &self, key: impl Into<String>, min: f64, max: f64, ) -> Result<i64>

ZCOUNT - 计算分数范围内的成员数量

Source

pub async fn zincrby( &self, key: impl Into<String>, increment: f64, member: impl Into<String>, ) -> Result<f64>

ZINCRBY - 将成员的分数增加指定数量

§返回

返回增加后的分数

Source

pub async fn zrank( &self, key: impl Into<String>, member: impl Into<String>, ) -> Result<Option<i64>>

ZRANK - 获取成员在有序集合中的排名(从低到高,0 为第一名)

§参数
  • key: 有序集合键
  • member: 成员
§返回
  • Ok(Some(i64)): 成员的排名(0 开始)
  • Ok(None): 成员不存在
Source

pub async fn zrevrank( &self, key: impl Into<String>, member: impl Into<String>, ) -> Result<Option<i64>>

ZREVRANK - 获取成员在有序集合中的逆序排名(从高到低,0 为第一名)

§参数
  • key: 有序集合键
  • member: 成员
§返回
  • Ok(Some(i64)): 成员的逆序排名(0 开始)
  • Ok(None): 成员不存在
Source

pub async fn zrevrange( &self, key: impl Into<String>, start: i64, stop: i64, ) -> Result<Vec<String>>

ZREVRANGE - 按索引范围从高到低获取有序集合的成员

§参数
  • key: 有序集合键
  • start: 起始索引
  • stop: 结束索引
§返回

指定范围内的成员列表(从高分到低分排序)

Source

pub async fn zrange_with_scores( &self, key: impl Into<String>, start: i64, stop: i64, ) -> Result<Vec<(String, f64)>>

ZRANGE WITHSCORES - 按索引范围获取有序集合的成员及其分数

§参数
  • key: 有序集合键
  • start: 起始索引
  • stop: 结束索引
§返回

成员和分数的元组列表(从低分到高分排序)

Source

pub async fn zrevrange_with_scores( &self, key: impl Into<String>, start: i64, stop: i64, ) -> Result<Vec<(String, f64)>>

ZREVRANGE WITHSCORES - 按索引范围从高到低获取有序集合的成员及其分数

§参数
  • key: 有序集合键
  • start: 起始索引
  • stop: 结束索引
§返回

成员和分数的元组列表(从高分到低分排序)

Source

pub async fn zremrangebyrank( &self, key: impl Into<String>, start: i64, stop: i64, ) -> Result<i64>

ZREMRANGEBYRANK - 移除有序集合中指定排名范围的成员

§参数
  • key: 有序集合键
  • start: 起始排名(0 为第一)
  • stop: 结束排名(-1 为最后一个)
§返回

被移除的成员数量

Source

pub async fn zremrangebyscore( &self, key: impl Into<String>, min: f64, max: f64, ) -> Result<i64>

ZREMRANGEBYSCORE - 移除有序集合中指定分数范围的成员

§参数
  • key: 有序集合键
  • min: 最小分数(包含)
  • max: 最大分数(包含)
§返回

被移除的成员数量

Source

pub async fn zscan( &self, key: impl Into<String>, cursor: i64, pattern: Option<&str>, count: Option<i64>, ) -> Result<(i64, Vec<(String, f64)>)>

ZSCAN - 增量式迭代有序集合中的成员

§参数
  • key: 有序集合键
  • cursor: 游标(初始传 0)
  • pattern: 可选的匹配模式
  • count: 可选的每批返回数量提示
§返回
  • Ok((i64, Vec<(String, f64)>)): (下一游标, 成员-分数对列表)
Source

pub async fn del(&self, keys: &[String]) -> Result<i64>

DEL - 删除一个或多个键

§返回

返回被删除的键数量

Source

pub async fn exists(&self, keys: &[String]) -> Result<i64>

EXISTS - 检查一个或多个键是否存在

§返回

返回存在的键数量

Source

pub async fn expire(&self, key: impl Into<String>, seconds: i64) -> Result<bool>

EXPIRE - 设置键的过期时间(秒)

§返回
  • Ok(true): 设置成功
  • Ok(false): 键不存在
Source

pub async fn ttl(&self, key: impl Into<String>) -> Result<i64>

TTL - 获取键的剩余生存时间(秒)

§返回
  • 正数: 剩余秒数
  • -1: 键存在但没有过期时间
  • -2: 键不存在
Source

pub async fn persist(&self, key: impl Into<String>) -> Result<bool>

PERSIST - 移除键的过期时间

§返回
  • Ok(true): 移除成功
  • Ok(false): 键不存在或没有过期时间
Source

pub async fn keys(&self, pattern: impl Into<String>) -> Result<Vec<String>>

KEYS - 查找所有匹配给定模式的键

§警告

此命令在生产环境中可能导致性能问题,请谨慎使用

§参数
  • pattern: 匹配模式(例如 “user:*”)
Source

pub async fn scan( &self, cursor: i64, pattern: Option<&str>, count: Option<i64>, ) -> Result<(i64, Vec<String>)>

SCAN - 增量式迭代数据库中的所有键

生产安全的 KEYS 替代方案,不会阻塞 Redis 服务器。

§参数
  • cursor: 游标(初始传 0,使用返回的游标继续迭代)
  • pattern: 可选的键名匹配模式(如 Some("user:*")
  • count: 可选的每批返回数量提示
§返回
  • Ok((i64, Vec<String>)): (下一游标, 本批键列表)
  • 游标为 0 表示完整迭代完成
§示例
let mut cursor = 0i64;
loop {
    let (next, keys) = client.scan(cursor, Some("user:*"), Some(100)).await?;
    // 处理 keys...
    cursor = next;
    if cursor == 0 { break; }
}
Source

pub async fn publish( &self, channel: impl Into<String>, message: impl Into<String>, ) -> Result<i64>

PUBLISH - 向指定频道发布消息

§参数
  • channel: 频道名称
  • message: 消息内容
§返回

接收到此消息的订阅者数量

Source

pub async fn health_check(&self) -> Result<bool>

健康检查 - 验证 Redis 连接是否正常

执行 PING 命令检查 Redis 服务可达性。连接异常时不抛错误,返回 Ok(false)。

§返回
  • Ok(true): Redis 连接正常
  • Ok(false): PING 响应异常
  • Err(DbError): 无法获取连接
Source

pub fn pool_status(&self) -> PoolStatus

获取连接池当前状态

§返回

PoolStatus 结构体,包含 max_size、size、available、waiting 统计信息

Source

pub fn script(&self, code: &str) -> Script

创建 Lua 脚本对象

返回 redis-rs 的原生 Script 类型,可用于执行 Lua 脚本。 Script 会自动处理 EVALSHA 和 EVAL 的回退机制。

§参数
  • code: Lua 脚本代码
§返回

redis::Script 对象

§示例
use yang_db::RedisClient;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = RedisClient::connect("redis://127.0.0.1:6379").await?;
     
    // 创建脚本:原子性地增加两个计数器
    let script = client.script(
        r#"
        redis.call('INCR', KEYS[1])
        redis.call('INCR', KEYS[2])
        return redis.call('GET', KEYS[1])
        "#
    );
     
    // 执行脚本
    let result: String = client.eval_script(
        &script,
        &["counter1".to_string(), "counter2".to_string()],
        &[]
    ).await?;
     
    println!("counter1 的值: {}", result);
    Ok(())
}
Source

pub async fn eval_script<T>( &self, script: &Script, keys: &[String], args: &[String], ) -> Result<T>
where T: FromRedisValue,

执行 Lua 脚本

使用 redis::Script 执行 Lua 脚本,自动处理 EVALSHA 和 EVAL 的回退。 脚本内的所有操作都是原子性的。

§参数
  • script: 脚本对象(通过 script() 方法创建)
  • keys: KEYS 参数列表(在脚本中通过 KEYS[1], KEYS[2] 访问)
  • args: ARGV 参数列表(在脚本中通过 ARGV[1], ARGV[2] 访问)
§返回
  • Ok(T): 脚本执行成功,返回类型化结果
  • Err(DbError): 脚本执行失败
§示例:原子性计数器增加
use yang_db::RedisClient;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = RedisClient::connect("redis://127.0.0.1:6379").await?;
     
    let script = client.script(
        r#"
        local current = redis.call('GET', KEYS[1])
        if not current then
            current = 0
        end
        local new_value = tonumber(current) + tonumber(ARGV[1])
        redis.call('SET', KEYS[1], new_value)
        return new_value
        "#
    );
     
    let result: i64 = client.eval_script(
        &script,
        &["my_counter".to_string()],
        &["10".to_string()]
    ).await?;
     
    println!("新值: {}", result);
    Ok(())
}
§示例:条件更新(乐观锁)
use yang_db::RedisClient;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = RedisClient::connect("redis://127.0.0.1:6379").await?;
     
    // 只有当余额足够时才扣减
    let script = client.script(
        r#"
        local balance = tonumber(redis.call('GET', KEYS[1]) or 0)
        local amount = tonumber(ARGV[1])
        if balance >= amount then
            redis.call('DECRBY', KEYS[1], amount)
            return 1
        else
            return 0
        end
        "#
    );
     
    let success: i64 = client.eval_script(
        &script,
        &["user:1000:balance".to_string()],
        &["100".to_string()]
    ).await?;
     
    if success == 1 {
        println!("扣款成功");
    } else {
        println!("余额不足");
    }
    Ok(())
}
§性能优化
  • 首次执行时,脚本会被发送到 Redis 服务器并缓存
  • 后续执行使用 EVALSHA 命令,只传输脚本的 SHA1 哈希值
  • 如果脚本不在缓存中,自动回退到 EVAL 命令

Trait Implementations§

Source§

impl Clone for RedisClient

Source§

fn clone(&self) -> RedisClient

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts 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 more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts 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
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more