2016-08-10 346 views
0

我试图找出如何如何在Rust中使用Redis存储/获取结构?

  1. programically实例化设定值的结构(其中之一可能是又一个嵌套的结构 - 或者不能) - 并将其保存在Redis
  2. 把它抓回来到一个结构从Redis的

我知道的是,2个性状ToRedisArgsFromRedisValue要在这里实现,但即使是我最简单的2个结构我不知道该怎么写IMPL他们在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的一名完全新手,我希望您至少能够帮助我了解一些如何实现这样的想法。

+0

除了“如何使用Rust *将数据存储在Redis中”之外,您似乎确实在问“如何在Redis中存储*此类数据*”。 MongoDB,Redis和传统的关系数据库都有不同的优势,它们不一定是相互替代的。我会说“我如何存储这种类型的数据”对于Stack Overflow来说太宽泛**,所以我建议你从你的问题中删除它。 – Shepmaster

回答

0

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

+0

恐怕这对我来说不太好,因为在mongodb上使用redis实时存储访问者会话状态数据的重点是 - 提高速度。我有点类似于sitecore共享和私人会话的工作方式,他们收集有关用户行为的数据,并在会话过期后将这些数据传输到数据库。所以会话数据会发生很多读取和更新,这就是json字符串序列化不是选项的原因。不过谢谢你的回答。 :-) – Dac0d3r