2016-08-10 342 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