Rust Crate 使用:rustbreak

rustbreak

Github
Crates.io

前言

持久化就是把數(shù)據(jù)保存到可掉電式存儲設備中以供之后使用。通常是將內(nèi)存中的數(shù)據(jù)存儲在關系型數(shù)據(jù)庫中,當然也可以存儲在磁盤文件、xml數(shù)據(jù)文件中。

介紹

RustBreak是一個簡單、快速、線程安全的輕量數(shù)據(jù)庫。開箱即用,你只要關心存儲內(nèi)容。

RustBreak支持三種數(shù)據(jù)序列化方式:ronbincode 、yaml

在某個應用程序中,將對部分數(shù)據(jù)持久化操作,并且任意數(shù)據(jù)格式的,可以考慮使用這個庫。

使用

通用流程:

  1. 創(chuàng)建或打開數(shù)據(jù)庫。 可以是文件數(shù)據(jù)庫、內(nèi)容數(shù)據(jù)庫、Mmap數(shù)據(jù)庫等。
  2. 對數(shù)據(jù)庫的讀寫操作。
  3. 同步數(shù)據(jù)庫。

實例

實驗目的,持久化HashMap數(shù)據(jù)到文件中。

cargo.toml文件中添加包:

[dependencies]
failure = "0.1.6"
serde = "1.0.23"
rustbreak = { git = "https://github.com/TheNeikos/rustbreak", features = ["ron_enc"] }

main.rs文件中實現(xiàn):

use std::{
    collections::HashMap,
    sync::Arc
};
use serde::{Serialize, Deserialize};
use rustbreak::{
    FileDatabase,
    deser::Ron
};


#[derive(Eq, PartialEq, Debug, Serialize, Deserialize, Clone)]
enum Country {
    Italy, UnitedKingdom
}

#[derive(Eq, PartialEq, Debug, Serialize, Deserialize, Clone)]
struct Person {
    name: String,
    country: Country,
}

fn main() -> Result<(), failure::Error> {
    let db = Arc::new(FileDatabase::<HashMap<String, Person>, Ron>::from_path("test.ron", HashMap::new())?);

    println!("Loading Database");
    db.load()?;

    println!("Writing to Database");
    let db1 = db.clone();
    let t1 = std::thread::spawn(move || {
        db1.write(|db| {
            db.insert("fred".into(), Person {
                name: String::from("Fred Johnson"),
                country: Country::UnitedKingdom
            });
        }).unwrap();
    });
    
    let db2 = db.clone();
    let t2 = std::thread::spawn(move || {
        db2.write(|db| {
            db.insert("john".into(), Person {
                name: String::from("John Andersson"),
                country: Country::Italy
            });
        }).unwrap();
    });

    t1.join().unwrap();
    t2.join().unwrap();

    println!("Syncing Database");
    db.save()?;

    db.read(|db| {
        println!("Results:");
        println!("{:#?}", db.get("john".into()));
    })?;
    
    Ok(())
}

首先定義Country枚舉類型和Person結構,并實現(xiàn)序列化。

接著啟動兩個線程插入數(shù)據(jù)。

輸出文件:

{
    "fred": (
        name: "Fred Johnson",
        country: UnitedKingdom,
    ),
    "john": (
        name: "John Andersson",
        country: Italy,
    ),
}
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容