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 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 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 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 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 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:*”)

Trait Implementations§

Source§

impl Clone for RedisClient

Source§

fn clone(&self) -> RedisClient

Returns a duplicate of the value. Read more
1.0.0 · 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