如何在Rust中使用Redis存储/获取结构?

时间:2016-08-10 00:53:06

标签: redis rust

我试图找出如何

  1. 以编程方式实例化具有设定值的结构(其中一个可能是另一个嵌套结构 - 或者不是) - 并将其保存在Redis
  2. 将其从Redis
  3. 中提取回结构中

    我知道这里将实现2个特征ToRedisArgsFromRedisValue,但即使对于我非常简单的2个结构,我也不知道在Rust中写什么来实现它们。我做了一个简单的例子:

    extern crate redis;
    use redis::Commands;
    
    // fn fetch_an_integer() -> redis::RedisResult<isize> {
    //     // connect to redis
    //     let client = try!(redis::Client::open("redis://127.0.0.1/"));
    //     let con = try!(client.get_connection());
    //     // throw away the result, just make sure it does not fail
    //     let _ : () = try!(con.set("my_key", 42));
    //     // read back the key and return it.  Because the return value
    //     // from the function is a result for integer this will automatically
    //     // convert into one.
    //     con.get("my_key")
    // }
    
    fn fetch_a_struct() -> redis::RedisResult<MyStruct> {
        // connect to redis
        let client = try!(redis::Client::open("redis://127.0.0.1/"));
        let con = try!(client.get_connection());
        // throw away the result, just make sure it does not fail
    
        let another_struct = AnotherStruct{x: "another_struct".to_string()};
        let mut my_vec: Vec<AnotherStruct> = Vec::new();
        my_vec.push(another_struct);
        let my_struct = MyStruct{x: "my_struct".to_string(), y: 1, z: my_vec};
    
        let _ : () = try!(con.set("my_key_struct", my_struct));
    
        con.get("my_key_struct")
    }
    
    fn main() {
        match fetch_a_struct() {
            Err(err) => {
                println!("{}", err)
            },
            Ok(x) => {
                println!("{}", x.x)
            }
        }
    
    }
    
    struct MyStruct {
        x: String,
        y: i64,
        z: Vec<AnotherStruct>,
    }
    
    struct AnotherStruct {
        x: String
    }
    

    Playground

    我需要在浏览我的网站时保存不同的访问者,他们的浏览行为(持续时间,访问过的页面和其他交互等)和其他统计信息 - 这就是我考虑使用Redis而不是MongoDB的原因,我的outproc会话商店。

    在MongoDB中,我有一个用户集合,交互集合等......但Redis中的等价方式是什么?

    作为Redis和Rust的完全新手,我希望你能帮助我,至少得到一些想法,如何实现这样的目标。

1 个答案:

答案 0 :(得分:0)

Serialize your data to a JSON string,将其另存为字符串,然后在需要时将其反序列化。