如何将删除关键字结果枚举打印为字符串

jgzswidk  于 2022-09-21  发布在  Redis
关注(0)|答案(2)|浏览(178)

我正在从redis中删除一个密钥,当使用rust时,这是代码的一部分,如下所示:

pub async fn del_redis_key(key: &str,) -> Result<()> {
    let config_redis_string = get_config("redisConnectionStr");
    let redis_con_string: &str = config_redis_string.as_str();
    let redis_client = redis::Client::open(redis_con_string).expect("can create redis client");
    let mut redis_conn = get_con(redis_client);
    let mut redis_conn_unwrap = redis_conn.unwrap();
    let del_result = redis_conn_unwrap.del(key).map_err(RedisCMDError)?;
    FromRedisValue::from_redis_value(&del_result).map_err(|e| RedisTypeError(e).into())
}

现在,我想将删除结果del_result作为字符串输出,我尝试将结果转换为json字符串,如下所示:

let result_json = serde_json::to_string(&del_result).unwrap();
println!("{}",result_json);

这似乎不起作用,因为第三方redis lib Value没有实现序列化特征,值代码如下所示:


# [derive(PartialEq, Eq, Clone)]

pub enum Value {
    /// A nil response from the server.
    Nil,
    /// An integer response.  Note that there are a few situations
    /// in which redis actually returns a string for an integer which
    /// is why this library generally treats integers and strings
    /// the same for all numeric responses.
    Int(i64),
    /// An arbitary binary data.
    Data(Vec<u8>),
    /// A bulk response of more data.  This is generally used by redis
    /// to express nested structures.
    Bulk(Vec<Value>),
    /// A status response.
    Status(String),
    /// A status response which represents the string "OK".
    Okay,
}

可以将删除结果作为字符串输出,以便输出到日志中吗?我正在使用Redis lib redis = "0.21.3"

ctrmrzij

ctrmrzij1#

SERDE实际上可以为远程结构派生。有关详细信息,请查看此链接:https://serde.rs/remote-derive.html

但在您的特定示例中,事情变得更加棘手。因为Value类型是递归的(Bulk(Vec<Value>))和currently you cannot use #[serde(with = ...)] inside a Vec

一种解决方法是为整个Vec<Value>类型定义您自己的序列化函数。下面是一个示例:https://github.com/serde-rs/serde/issues/1211

我已经为您实现了此方法。不过,这并不是一帆风顺的。

use redis::Value;
use serde::Serialize;

# [derive(Serialize)]

# [serde(remote = "Value")]

pub enum ValueRef {
    Nil,
    Int(i64),
    Data(Vec<u8>),
    #[serde(with = "redis_value_vec")]
    Bulk(Vec<Value>),
    Status(String),
    Okay,
}

mod redis_value_vec {
    use super::ValueRef;
    use redis::Value;
    use serde::{Serialize, Serializer};

    pub fn serialize<S: Serializer>(array: &[Value], serializer: S) -> Result<S::Ok, S::Error> {
        #[derive(Serialize)]
        struct W<'a>(#[serde(with = "ValueRef")] &'a Value);

        serializer.collect_seq(array.iter().map(W))
    }
}

fn main() {
    #[derive(Serialize)]
    struct W<'a>(#[serde(with = "ValueRef")] &'a Value);

    let val = Value::Nil;
    println!("{}", serde_json::to_string(&W(&val)).unwrap());
}

我建议您向该机箱提交PR,添加serde功能,可选地启用此派生。这是很常见的。

z9smfwbn

z9smfwbn2#

如果您要做的只是打印结果以用于日志记录,则可以使用ValueimplementsDebug。因此,您可以使用调试格式说明符将其打印出来:

println!("{:?}", del_result);

相关问题