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
impl RedisTransaction
Sourcepub fn new(client: RedisClient) -> Self
pub fn new(client: RedisClient) -> Self
Sourcepub fn hset(
&mut self,
key: impl Into<String>,
field: impl Into<String>,
value: impl Into<String>,
) -> &mut Self
pub fn hset( &mut self, key: impl Into<String>, field: impl Into<String>, value: impl Into<String>, ) -> &mut Self
Sourcepub async fn exec<T: FromRedisValue>(self) -> Result<T>
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?;Sourcepub async fn execute(self) -> Result<Vec<RedisValue>>
pub async fn execute(self) -> Result<Vec<RedisValue>>
Auto Trait Implementations§
impl Freeze for RedisTransaction
impl !RefUnwindSafe for RedisTransaction
impl Send for RedisTransaction
impl Sync for RedisTransaction
impl Unpin for RedisTransaction
impl UnsafeUnpin for RedisTransaction
impl !UnwindSafe for RedisTransaction
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
Mutably borrows from an owned value. Read more
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>
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 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>
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