解决数据问题-内存数据库

tokio-store_mini_redis.png

值存储 Entry

  1. struct Entry {
  2. // 唯一索引
  3. id: u64,
  4. // 字节数据
  5. data: Bytes,
  6. // 数据过期时间,可选参数
  7. expires_at: Option<Instant>,
  8. }
  9. struct Entry {
  10. id: u64,
  11. data: Bytes,
  12. expires_at: Option<Instant>,
  13. }
  • 数据进入redis会被赋予一个唯一索引id
  • 数据以字节数组中的形式存储在data字段中
  • 过期时间存在expires_at中,如果没有过期时间这个字段就是None

    多功能支持-存储状态中心

    ```rust struct State { // 键值对存储 entries: HashMap, // 订阅发布广播通道存储 pub_sub: HashMap>, // 支持按键排序的键值对存储,用于记录过期状态 // 键如此设计的原因(Instant,u64):保证过期数据的唯一性 expirations: BTreeMap<(Instant, u64), String>, // 全局 id 对过期数据 next_id: u64, // 标记数据库实例的运行状态 // 当全部的Db values drop,这个信号量被设置为true shutdown: bool, }

struct State { entries: HashMap, pub_sub: HashMap>, expirations: BTreeMap<(Instant, u64), String>, next_id: u64, shutdown: bool, }

  1. <a name="JGl7A"></a>
  2. ## 线程安全的保障Mutex
  3. ```rust
  4. use std::sync::{Mutex};
  5. struct Shared {
  6. // 保证线程安全的存储访问
  7. state: Mutex<State>,
  8. // 处理过期的后台任务
  9. background_task: Notify,
  10. }
  11. use std::sync::{Mutex};
  12. struct Shared {
  13. state: Mutex<State>,
  14. background_task: Notify,
  15. }

线程间共享 Arc

  1. pub(crate) struct Db {
  2. shared: Arc<Shared>
  3. }

最后的装饰类 DbDropGuard

  1. pub(crate) struct DbDropGuard {
  2. db: Db
  3. }