spring-redis插件

spring-redis是针对redis-rs的自动装配

crates.io Documentation

依赖

spring-redis = { version = "<version>" }

配置项

[redis]
uri = "redis://127.0.0.1/"        # redis 数据库地址

# 下面都是可选配置
connection_timeout = 10000        # 连接超时时间,单位毫秒
response_timeout = 1000           # 响应超时时间,单位毫秒
number_of_retries = 6             # 重试次数,间隔时间按指数增长
exponent_base = 2                 # 间隔时间指数基数,单位毫秒
factor = 100                      # 间隔时间增长因子,默认100倍增长
max_delay = 60000                 # 最大间隔时间

组件

配置完上述配置项后,插件会自动注册一个Redis连接管理对象。该对象是redis::aio::ConnectionManager的别名。

pub type Redis = redis::aio::ConnectionManager;

提取插件注册的Component

RedisPlugin插件为我们自动注册了一个连接管理对象,我们可以使用Component从AppState中提取这个连接池,Component是一个axum的extractor

async fn list_all_redis_key(Component(mut redis): Component<Redis>) -> Result<impl IntoResponse> {
    let keys: Vec<String> = redis.keys("*").await.context("redis request failed")?;
    Ok(Json(keys))
}

cache

spring-redis提供了基于 Redis 的异步函数透明缓存。在async方法上添加cache宏即可对函数结果进行缓存。

示例如下:

#[cache("redis-cache:{key}", expire = 60, condition = key.len() > 3)]
async fn cachable_func(key: &str) -> String {
    format!("cached value for key: {key}")
}

cache宏支持expireconditionunless三个可选参数。具体可以参考cache文档。

cache包装的函数需满足以下要求:

  • 必须是 async fn
  • 可以返回 Result<T, E> 或普通值 T
  • 返回类型必须实现 serde::Serializeserde::Deserialize,底层使用serde_json进行序列化

完整代码参考redis-example