如何重用redis连接?

How to reuse the redis connection?

我正在尝试连接到 Redis。这是我的代码的样子:

#[get("/v1.1/playlist/detail/<req_playlist_id>")]
pub async fn playlist_detail_attr(req_playlist_id: i64, loginUserInfo: LoginUserInfo) -> content::Json<String> {
    let playlistKey = "music:playlist:";
    let keyResult = format!("{}{}", playlistKey, loginUserInfo.userId);
    const REDIS_CON_STRING: &str = "redis://AoGTmVy3U7@cruise-redis-master.reddwarf-cache.svc.cluster.local:6379";
    let redis_client = redis::Client::open(REDIS_CON_STRING).expect("can create redis client");
    let mut redis_conn = get_con(redis_client);
    let cached_playlist = get_str(&mut redis_conn.as_ref().unwrap(), &keyResult).await;
    return if cached_playlist.as_ref().unwrap().is_empty() {
        let playlistDetail = query_playlist_detail(req_playlist_id).await;
        let res = ApiResponse {
            result: playlistDetail,
            ..Default::default()
        };
        let response_json = serde_json::to_string(&res).unwrap();
        set_str(&mut redis_conn.unwrap(), &keyResult, &response_json, 60*60*24*7);
        content::Json(response_json)
    } else {
        content::Json(cached_playlist.unwrap())
    }
}

如果缓存的键为空,我想在查询redis操作和设置redis操作中重用redis_conn。当我编译这段代码时,它显示错误:

error[E0596]: cannot borrow data in a `&` reference as mutable
  --> src/biz/music/playlist_controller.rs:21:35
   |
21 |     let cached_playlist = get_str(&mut redis_conn.as_ref().unwrap(), &keyResult).await;
   |                                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot borrow as mutable

我认为 as_ref()as_mut() 不是必需的,因为您指定了一个可变借用,使用 &mut,将其作为参数传递给 redis_conn函数 get_str。此外,在 get_con 末尾添加 unwrap() 将在使用 redis_conn 的地方保存 'unwrap()' 对 redis_conn 的调用。也就是说,更改如下所示。试一试。

let mut redis_conn = get_con(redis_client).unwrap();
let cached_playlist = get_str(&mut redis_conn, &keyResult).await;