前言

单位上有个 Rust 项目,orm 选型很长时间都没定下来,故先设计了抽象的仓储层方便写业务逻辑。

设计抽象接口

抽象只读接口,仅读取使用,目前需求仅用查询 id、查询全部和按名称搜索,当然理应设计上分页。

//! read_only_repository.rs
/// 只读仓储,对仅限读取的仓储进行抽象
#[async_trait::async_trait]
pub trait IReadOnlyRepository<T>
where
T: std::marker::Send,
{
/// 根据 id 获取唯一对象
async fn get_by_id(&self, id: &str) -> anyhow::Result<T>;
/// 获取所有对象
async fn get_all(&self) -> anyhow::Result<Vec<T>>;
/// 根据名称搜索
async fn search_by_name(&self, &str) -> anyhow::Result<Vec<T>>;
}

抽象可变接口,目前仅考虑了插入、修改、删除以及事务提交。

//! mutable_repository.rs
/// 可变仓储,对修改数据的仓储进行抽象
#[async_trait::async_trait]
pub trait IMutableRepository<T>
where
T: std::marker::Send,
{
/// 更新数据
async fn update(&self, entity: T) -> anyhow::Result<T>;
/// 插入数据
async fn insert(&self, entity: T) -> anyhow::Result<T>;
/// 删除数据
async fn delete(&self, entity: T) -> anyhow::Result<bool>;
/// 使用 uuid 删除数据,`entity` 是用于指示当前实现类型的泛型模板,防止 Rust 产生方法重载的问题,
/// 但对于大多数数据库可尝试使用以下代码:
/// ``` no_run
/// // 建立一个空的枚举用于指示类型
/// let n: Option<TYPE> = None;
/// self.delete_by_id(entity.id.as_str(), n).await?;
/// ```
async fn delete_by_id(&self, uuid: &str, entity: Option<T>) -> anyhow::Result<bool>;
/// 提交变更,在带有事务的数据库将提交事务,否则该方法应该仅返回 `Ok(true)`
///
async fn save_changed(&self) -> anyhow::Result<bool>;
}

租约仓储,为了支持非关系型数据库用的,或许会用到租约(生存时间)。

//! lease_repository.rs
/// 租约仓储,对带有租约的仓储进行抽象
#[async_trait::async_trait]
pub trait ILeaseRepository<T>
where
T: std::marker::Send,
{
/// 更新数据并更新租约
async fn update_with_lease(&self, key: &str, entity: T, ttl: i64) -> anyhow::Result<T>;
/// 插入数据并设定租约
async fn insert_with_lease(&self, key: &str, entity: T, ttl: i64) -> anyhow::Result<T>;
/// 延长特定数据的租约
async fn keep_alive(&self, key: &str) -> anyhow::Result<bool>;
}

最终整合的接口。

//! mod.rs
/// 对使用数据库仓储的抽象,带有可读仓储和可写仓储
#[async_trait::async_trait]
pub trait IDBRepository<T>: IReadOnlyRepository<T> + IMutableRepository<T>
where
T: std::marker::Send,
{
} /// 对使用带有租约的数据库进行抽象,带有租约仓储、可读仓储和可写仓储
#[async_trait::async_trait]
pub trait ILeaseDBRepository<T>: IDBRepository<T> + ILeaseRepository<T>
where
T: std::marker::Send,
{
}

简单实现

泛型具体用起来有一定的生命周期的问题,解决问题的方法也并不难,加控制生命周期的标记。但我目前的实现方案为使用 marco 自动为每个实体类型生成代码。在这里我个人本地暂且先用了 etcd 数据库作为基础实现。

可变仓储的实现:

    /// 针对 Etcd 数据库实现只读仓储 `repository::IMutableRepository`
///
/// struct 要求带有字段 `client: std::sync::Arc<etcd_client::Client>`
#[macro_export]
macro_rules! impl_etcd_mutable_repository {
($base_struct: ty, $domain: ty) => {
#[async_trait::async_trait]
impl IMutableRepository<$domain> for $base_struct {
async fn update(&self, entity: $domain) -> anyhow::Result<$domain> {
let mut kv_client = self.client.kv_client();
let key = format!("test_{}_{}", stringify!($domain), entity.id);
kv_client
.put(
key,
Into::<Vec<u8>>::into(serde_json::to_vec(&entity).unwrap()),
None,
)
.await?;
Ok(entity)
}
async fn insert(&self, entity: $domain) -> anyhow::Result<$domain> {
self.update(entity).await
}
async fn delete(&self, entity: $domain) -> anyhow::Result<bool> {
let n: Option<$domain> = None;
self.delete_by_id(entity.id.as_str(), n).await
}
async fn delete_by_id(
&self,
uuid: &str,
entity: Option<$domain>,
) -> anyhow::Result<bool> {
let mut kv_client = self.client.kv_client();
let key = format!("test_{}_{}", stringify!($domain), uuid);
match kv_client.delete(key, None).await {
Ok(x) => Ok(true),
Err(e) => anyhow::bail!(e),
}
}
async fn save_changed(&self) -> anyhow::Result<bool> {
Ok(true)
}
}
};
}

具体应用:

use crate::repository::*;
pub struct EtcdRepository {
client: std::sync::Arc<etcd_client::Client>,
}
impl EtcdRepository {
pub fn new(client: std::sync::Arc<etcd_client::Client>) -> Self {
Self { client }
}
}
impl_etcd_mutable_repository!(
EtcdRepository,
crate::models::UserInfo
);

调用

use crate::models::*;
use crate::repository::IMutableDBRepository; pub struct UserInfoService {
user_info_repository: std::sync::Arc<dyn IMutableRepository<UserInfo> + Send + Sync>,
} impl HeartbeatService {
pub fn new(
user_info_repository: std::sync::Arc<dyn IMutableRepository<UserInfo> + Send + Sync>,
) -> Self {
return Self { user_info_repository };
}
} #[async_trait::async_trait]
pub trait IPluginManagementService {
async fn list_user_infos(&self) -> Result<Vec<UserInfo>>;
} #[async_trait::async_trait]
impl IPluginManagementService for PluginManagementService {
async fn list_user_infos(&self) -> Result<Vec<UserInfo>> {
self.user_info_repository.get_all().await
}
}

参考

  1. Rustでクリーンアーキテクチャを組む時DIするサンプルコード
  2. Crate etcd_client

在 Rust 中实现 Repository 仓储模式的更多相关文章

  1. 从Entity Framework的实现方式来看DDD中的repository仓储模式运用

    一:最普通的数据库操作 static void Main(string[] args) { using (SchoolDBEntities db = new SchoolDBEntities()) { ...

  2. 6.在MVC中使用泛型仓储模式和依赖注入实现增删查改

    原文链接:http://www.c-sharpcorner.com/UploadFile/3d39b4/crud-operations-using-the-generic-repository-pat ...

  3. 5.在MVC中使用泛型仓储模式和工作单元来进行增删查改

    原文链接:http://www.c-sharpcorner.com/UploadFile/3d39b4/crud-operations-using-the-generic-repository-pat ...

  4. MVC中使用泛型仓储模式和依赖注入

    在ASP.NET MVC中使用泛型仓储模式和依赖注入,实现增删查改 原文链接:http://www.codeproject.com/Articles/838097/CRUD-Operations-Us ...

  5. 在MVC中使用泛型仓储模式和工作单元来进行增删查改

    原文链接:http://www.c-sharpcorner.com/UploadFile/3d39b4/crud-operations-using-the-generic-repository-pat ...

  6. 在MVC中使用泛型仓储模式和依赖注入实现增删查改

    标签: 原文链接:http://www.c-sharpcorner.com/UploadFile/3d39b4/crud-operations-using-the-generic-repository ...

  7. DDD之:Repository仓储模式

    在DDD设计中大家都会使用Repository pattern来获取domain model所需要的数据. 1.什么事Repository? "A Repository mediates b ...

  8. 4.在MVC中使用仓储模式进行增删查改

    原文链接:http://www.c-sharpcorner.com/UploadFile/3d39b4/crud-using-the-repository-pattern-in-mvc/ 系列目录: ...

  9. MVC5+EF6 入门完整教程十一:细说MVC中仓储模式的应用

    摘要: 第一阶段1~10篇已经覆盖了MVC开发必要的基本知识. 第二阶段11-20篇将会侧重于专题的讲解,一篇文章解决一个实际问题. 根据园友的反馈, 本篇文章将会先对呼声最高的仓储模式进行讲解. 文 ...

  10. MVC5+EF6 入门完整教程11--细说MVC中仓储模式的应用

    摘要: 第一阶段1~10篇已经覆盖了MVC开发必要的基本知识. 第二阶段11-20篇将会侧重于专题的讲解,一篇文章解决一个实际问题. 根据园友的反馈, 本篇文章将会先对呼声最高的仓储模式进行讲解. 文 ...

随机推荐

  1. 全球权威的 IT 研究公司 Gartner,发布未来五大隐私趋势

    Gartner(高德纳) 公司是全球最具权威的 IT 研究与顾问咨询公司之一,它成立于 1979 年,总部设在美国康涅狄克州斯坦福.其研究范围覆盖全部 IT 产业,包括 IT 的研究.发展.评估.应用 ...

  2. k3s 基础 —— 配置 loki

    官方文档 核心组件 3 个 chart: promtail 这是一个 agent 代理客户端,用于收集日志,将日志传送给 loki loki 核心组件,主要功能是日志数据的写入与分析.包含 gatew ...

  3. python笔记:第二章基本数据类型

    基本数据类型 Python中的数据类型可以分为五大类:字符串.数字.容器.布尔.None 1.字符串 可以使用单引号或双引号创建字符串,可以用加号将两个字符串合并 name = '小明' age = ...

  4. 音视频开发进阶——YUV与RGB的采样与存储格式

    在上一篇文章中,我们带大家了解了视频.图像.像素和色彩之间的关系,还初步认识了两种常用的色彩空间,分别是大家比较熟悉的 RGB,以及更受视频领域青睐的 YUV.今天,我们将继续深入学习 RGB.YUV ...

  5. Java扩展Nginx之六:两大filter

    欢迎访问我的GitHub 这里分类和汇总了欣宸的全部原创(含配套源码):https://github.com/zq2599/blog_demos 本篇概览 本文是<Java扩展Nginx> ...

  6. SAS - PROC FCMP

    PROC FCMP 概述 PROC FCMP 可用于自定义函数(funcion)和子程序(subroutines).自定义函数和子程序的名称的最大长度为 32,长度超过 32 的名称虽然可以定义,但无 ...

  7. 使用sqlplus

    1. 执行一个SQL脚本文件 SQL>start file_name SQL>@ file_name 可以将多条sql语句保存在一个文本文件中,这样当要执行这个文件中的所有的sql语句时, ...

  8. cesium加载gif图片(cesium篇.43)

    https://blog.csdn.net/QQ98281642/article/details/120214325

  9. 传输层之UDP与TCP的首部

    从通信信息处理的角度看,运输层向它上面的应用层提供通信服务,它属于面向通信部分的最高层,同时也是用户功能的最底层. 传输层位于应用层和数据链路层之间,主要有两个协议,用户数据报协议UDP(User D ...

  10. NFS快速入门(一):简介、原理

    NFS网络文件共享存储 什么是NFS NFS 是 Network File System 的缩写,中文意思是网络文件系统.它的主要功能是通过网络(一般是局域网)让不同主机系统之间可以共享文件或目录.N ...