use crate::{DbError, RedisClient, RedisValue, Result};
use redis::FromRedisValue;
pub struct RedisTransaction {
client: RedisClient,
pipe: redis::Pipeline,
watched_keys: Vec<String>,
}
fn is_watch_conflict(raw: &redis::Value, has_watched_keys: bool) -> bool {
has_watched_keys && matches!(raw, redis::Value::Nil)
}
fn is_exec_abort_error(error: &redis::RedisError) -> bool {
matches!(error.kind(), redis::ErrorKind::ExecAbortError)
|| error.to_string().contains("EXECABORT")
}
impl RedisTransaction {
pub fn new(client: RedisClient) -> Self {
let mut pipe = redis::pipe();
pipe.atomic();
Self {
client,
pipe,
watched_keys: Vec::new(),
}
}
pub fn watch(&mut self, keys: &[String]) -> &mut Self {
self.watched_keys.extend_from_slice(keys);
self
}
pub fn set(&mut self, key: impl Into<String>, value: impl Into<String>) -> &mut Self {
self.pipe.set(key.into(), value.into());
self
}
pub fn get(&mut self, key: impl Into<String>) -> &mut Self {
self.pipe.get(key.into());
self
}
pub fn del(&mut self, keys: &[String]) -> &mut Self {
self.pipe.del(keys);
self
}
pub fn incr(&mut self, key: impl Into<String>) -> &mut Self {
self.pipe.incr(key.into(), 1);
self
}
pub fn decrby(&mut self, key: impl Into<String>, decrement: i64) -> &mut Self {
self.pipe.decr(key.into(), decrement);
self
}
pub fn hset(
&mut self,
key: impl Into<String>,
field: impl Into<String>,
value: impl Into<String>,
) -> &mut Self {
self.pipe.hset(key.into(), field.into(), value.into());
self
}
pub fn hget(&mut self, key: impl Into<String>, field: impl Into<String>) -> &mut Self {
self.pipe.hget(key.into(), field.into());
self
}
pub fn lpush(&mut self, key: impl Into<String>, values: &[String]) -> &mut Self {
if !values.is_empty() {
self.pipe.lpush(key.into(), values);
}
self
}
pub fn rpush(&mut self, key: impl Into<String>, values: &[String]) -> &mut Self {
if !values.is_empty() {
self.pipe.rpush(key.into(), values);
}
self
}
pub fn sadd(&mut self, key: impl Into<String>, members: &[String]) -> &mut Self {
if !members.is_empty() {
self.pipe.sadd(key.into(), members);
}
self
}
pub fn zadd(&mut self, key: impl Into<String>, members: &[(f64, String)]) -> &mut Self {
if !members.is_empty() {
let pairs: Vec<(f64, &str)> = members.iter().map(|(s, m)| (*s, m.as_str())).collect();
self.pipe.zadd_multiple(key.into(), &pairs);
}
self
}
pub fn cmd(&mut self, cmd: redis::Cmd) -> &mut Self {
self.pipe.add_command(cmd);
self
}
#[tracing::instrument(
name = "db.query",
skip_all,
fields(db.system = "redis", db.operation = "transaction", otel.kind = "client")
)]
pub async fn exec<T: FromRedisValue>(self) -> Result<T> {
let mut conn = self
.client
.pool()
.get()
.await
.map_err(|e| DbError::RedisPoolError(format!("获取连接失败: {}", e)))?;
const MAX_RETRIES: usize = 100;
let mut retries = 0;
loop {
if !self.watched_keys.is_empty() {
let mut watch_cmd = redis::cmd("WATCH");
for key in &self.watched_keys {
watch_cmd.arg(key);
}
watch_cmd
.query_async::<()>(&mut *conn)
.await
.map_err(|e| DbError::RedisCommandError(format!("WATCH 命令失败: {}", e)))?;
}
match self.pipe.query_async::<redis::Value>(&mut *conn).await {
Ok(raw) => {
if is_watch_conflict(&raw, !self.watched_keys.is_empty()) {
retries += 1;
if retries >= MAX_RETRIES {
return Err(DbError::RedisCommandError(format!(
"事务执行失败:WATCH 冲突已重试 {} 次",
MAX_RETRIES
)));
}
conn = self.client.pool().get().await.map_err(|e| {
DbError::RedisPoolError(format!("重试获取连接失败: {}", e))
})?;
continue;
}
return T::from_redis_value(&raw).map_err(|e| {
DbError::RedisCommandError(format!("事务结果解码失败: {}", e))
});
}
Err(e) => {
let is_exec_abort = is_exec_abort_error(&e);
if is_exec_abort && !self.watched_keys.is_empty() {
retries += 1;
if retries >= MAX_RETRIES {
return Err(DbError::RedisCommandError(format!(
"事务执行失败,已重试 {} 次: {}",
MAX_RETRIES, e
)));
}
conn = self.client.pool().get().await.map_err(|e| {
DbError::RedisPoolError(format!("重试获取连接失败: {}", e))
})?;
continue;
} else {
return Err(DbError::RedisCommandError(format!("事务执行失败: {}", e)));
}
}
}
}
}
#[tracing::instrument(
name = "db.query",
skip_all,
fields(db.system = "redis", db.operation = "transaction", otel.kind = "client")
)]
pub async fn execute(self) -> Result<Vec<RedisValue>> {
let results: Vec<redis::Value> = self.exec().await?;
Ok(results.into_iter().map(RedisValue::from).collect())
}
pub fn len(&self) -> usize {
self.pipe.cmd_iter().count()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}
#[cfg(test)]
mod tests {
use super::{is_exec_abort_error, is_watch_conflict};
#[test]
fn test_transaction_creation() {
}
#[test]
fn test_is_watch_conflict() {
assert!(is_watch_conflict(&redis::Value::Nil, true));
assert!(!is_watch_conflict(&redis::Value::Nil, false));
assert!(!is_watch_conflict(&redis::Value::Int(1), true));
assert!(!is_watch_conflict(
&redis::Value::Array(vec![redis::Value::Int(1)]),
true
));
}
#[test]
fn test_is_exec_abort_error_distinguishes_error_kinds() {
let exec_abort =
redis::RedisError::from((redis::ErrorKind::ExecAbortError, "事务因先前错误被丢弃"));
let type_error = redis::RedisError::from((redis::ErrorKind::TypeError, "返回值类型不匹配"));
assert!(is_exec_abort_error(&exec_abort));
assert!(!is_exec_abort_error(&type_error));
}
}