Skip to main content

RedisTransaction

Struct RedisTransaction 

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

Redis 事务构建器

提供类型安全的 Redis 事务操作接口,基于 WATCH/MULTI/EXEC 机制实现乐观锁。

§特性

  • 支持 WATCH 键监视(乐观锁)
  • 原子性执行所有命令
  • 自动处理 WATCH 冲突并重试
  • 支持所有 Redis 命令

§示例

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");
    tx.set("key2", "value2");
    tx.incr("counter");
     
    // 执行事务
    let results: (String, String, i64) = tx.exec().await?;
    println!("事务执行结果: {:?}", results);
     
    Ok(())
}

Implementations§

Source§

impl RedisTransaction

Source

pub fn new(client: RedisClient) -> Self

创建新的事务

§参数
  • client: Redis 客户端
§返回

新的事务实例

Source

pub fn watch(&mut self, keys: &[String]) -> &mut Self

监视一个或多个键(用于乐观锁)

§参数
  • keys: 要监视的键列表
§返回

返回 self 以支持链式调用

§注意
  • 如果被监视的键在事务执行前被修改,事务将被取消并自动重试
  • 必须在添加命令之前调用
§示例
let mut tx = client.transaction();
tx.watch(&["balance".to_string()]);
Source

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

添加 SET 命令

§参数
  • key: 键
  • value: 值
§返回

返回 self 以支持链式调用

Source

pub fn get(&mut self, key: impl Into<String>) -> &mut Self

添加 GET 命令

§参数
  • key: 键
§返回

返回 self 以支持链式调用

Source

pub fn del(&mut self, keys: &[String]) -> &mut Self

添加 DEL 命令

§参数
  • keys: 要删除的键列表
§返回

返回 self 以支持链式调用

Source

pub fn incr(&mut self, key: impl Into<String>) -> &mut Self

添加 INCR 命令

§参数
  • key: 键
§返回

返回 self 以支持链式调用

Source

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

添加 DECRBY 命令

§参数
  • key: 键
  • decrement: 减少的数量
§返回

返回 self 以支持链式调用

Source

pub fn hset( &mut self, key: impl Into<String>, field: impl Into<String>, value: impl Into<String>, ) -> &mut Self

添加 HSET 命令

§参数
  • key: 哈希表键
  • field: 字段名
  • value: 字段值
§返回

返回 self 以支持链式调用

Source

pub fn hget( &mut self, key: impl Into<String>, field: impl Into<String>, ) -> &mut Self

添加 HGET 命令

§参数
  • key: 哈希表键
  • field: 字段名
§返回

返回 self 以支持链式调用

Source

pub fn lpush(&mut self, key: impl Into<String>, values: &[String]) -> &mut Self

添加 LPUSH 命令

§参数
  • key: 列表键
  • values: 要插入的值列表
§返回

返回 self 以支持链式调用

Source

pub fn rpush(&mut self, key: impl Into<String>, values: &[String]) -> &mut Self

添加 RPUSH 命令

§参数
  • key: 列表键
  • values: 要插入的值列表
§返回

返回 self 以支持链式调用

Source

pub fn sadd(&mut self, key: impl Into<String>, members: &[String]) -> &mut Self

添加 SADD 命令

§参数
  • key: 集合键
  • members: 要添加的成员列表
§返回

返回 self 以支持链式调用

Source

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

添加 ZADD 命令

§参数
  • key: 有序集合键
  • members: (分数, 成员) 元组列表
§返回

返回 self 以支持链式调用

Source

pub fn cmd(&mut self, cmd: Cmd) -> &mut Self

添加自定义命令

§参数
  • cmd: Redis 命令
§返回

返回 self 以支持链式调用

Source

pub async fn exec<T: FromRedisValue>(self) -> Result<T>

执行事务(类型化版本)

§类型参数
  • T: 实现了 FromRedisValue 的类型
§返回
  • Ok(T): 事务执行成功,返回结果
  • Err(DbError): 事务执行失败
§错误处理
  • 如果 WATCH 的键被修改,自动重试(最多 100 次)
  • 如果其他错误,直接返回
§示例
let mut tx = client.transaction();
tx.set("key1", "value1")
  .set("key2", "value2")
  .get("key1");

// 获取类型化结果
let results: (String, String, String) = tx.exec().await?;
Source

pub async fn execute(self) -> Result<Vec<RedisValue>>

执行事务(兼容模式)

§返回
  • Ok(Vec<RedisValue>): 事务执行成功,返回结果列表
  • Err(DbError): 事务执行失败
§示例
let mut tx = client.transaction();
tx.set("key1", "value1")
  .set("key2", "value2")
  .incr("counter");

let results = tx.execute().await?;
println!("事务执行结果: {:?}", results);
Source

pub fn len(&self) -> usize

获取事务中的命令数量

§返回

事务中的命令数量

Source

pub fn is_empty(&self) -> bool

检查事务是否为空

§返回
  • true: 事务为空
  • false: 事务不为空

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> 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, 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