0279-KVS-新增日志操作模块

环境

  • Time 2022-12-11
  • WSL-Ubuntu 22.04
  • Rust 1.65.0

前言

说明

参考:https://github.com/pingcap/talent-plan

目标

在上一节的基础上,新增日志操作模块,将操作命令转为 JSON。

Cargo.toml

[package]
edition = "2021"
name = "kvs"
version = "1.0.0"

[dependencies]
clap = {version = "4", features = ["derive"]}
serde = {version = "1", features = ["derive"]}
serde_json = "1"

lib.rs

use cmd::Command;
use log::CommandLog;

mod cmd;
mod log;

#[derive(Default)]
pub struct KvStore {
    log: CommandLog,
}

impl KvStore {
    pub fn get(&mut self, key: &str) -> Option<String> {
        self.log.get(key)
    }

    pub fn set(&mut self, key: String, value: String) -> Option<String> {
        let command = Command::Set { key, value };
        self.log.set(command)
    }

    pub fn remove(&mut self, key: String) -> Option<String> {
        let command = Command::Remove { key };
        self.log.remove(command)
    }
}

log.rs

use crate::cmd::Command;

#[derive(Default)]
pub struct CommandLog {}

impl CommandLog {
    pub fn get(&mut self, _: &str) -> Option<String> {
        None
    }

    pub fn set(&mut self, command: Command) -> Option<String> {
        let json = serde_json::to_string(&command).unwrap();
        dbg!(json);
        None
    }

    pub fn remove(&mut self, command: Command) -> Option<String> {
        let json = serde_json::to_string(&command).unwrap();
        dbg!(json);
        None
    }
}

运行

使用 cargo build --release 构建后运行。

root@jiangbo12490:~/git/game/target/release# ./kvs set name JiangBo
[src/log.rs:13] json = "{\"Set\":{\"key\":\"name\",\"value\":\"JiangBo\"}}"
SET KEY: name, VALUE: None
root@jiangbo12490:~/git/game/target/release# ./kvs set age 44
[src/log.rs:13] json = "{\"Set\":{\"key\":\"age\",\"value\":\"44\"}}"
SET KEY: age, VALUE: None
root@jiangbo12490:~/git/game/target/release# ./kvs get name
GET KEY: name, VALUE: None
root@jiangbo12490:~/git/game/target/release# ./kvs rm name
[src/log.rs:19] json = "{\"Remove\":{\"key\":\"name\"}}"
REM KEY: name, VALUE: None

总结

将操作转为命令对象,并且新增了日志操作,将命令对象转为 JSON。

附录

posted @ 2025-10-27 10:33  jiangbo4444  阅读(4)  评论(0)    收藏  举报