在 Rust 中实现 Repository 仓储模式
前言
单位上有个 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
}
}
参考
在 Rust 中实现 Repository 仓储模式的更多相关文章
- 从Entity Framework的实现方式来看DDD中的repository仓储模式运用
一:最普通的数据库操作 static void Main(string[] args) { using (SchoolDBEntities db = new SchoolDBEntities()) { ...
- 6.在MVC中使用泛型仓储模式和依赖注入实现增删查改
原文链接:http://www.c-sharpcorner.com/UploadFile/3d39b4/crud-operations-using-the-generic-repository-pat ...
- 5.在MVC中使用泛型仓储模式和工作单元来进行增删查改
原文链接:http://www.c-sharpcorner.com/UploadFile/3d39b4/crud-operations-using-the-generic-repository-pat ...
- MVC中使用泛型仓储模式和依赖注入
在ASP.NET MVC中使用泛型仓储模式和依赖注入,实现增删查改 原文链接:http://www.codeproject.com/Articles/838097/CRUD-Operations-Us ...
- 在MVC中使用泛型仓储模式和工作单元来进行增删查改
原文链接:http://www.c-sharpcorner.com/UploadFile/3d39b4/crud-operations-using-the-generic-repository-pat ...
- 在MVC中使用泛型仓储模式和依赖注入实现增删查改
标签: 原文链接:http://www.c-sharpcorner.com/UploadFile/3d39b4/crud-operations-using-the-generic-repository ...
- DDD之:Repository仓储模式
在DDD设计中大家都会使用Repository pattern来获取domain model所需要的数据. 1.什么事Repository? "A Repository mediates b ...
- 4.在MVC中使用仓储模式进行增删查改
原文链接:http://www.c-sharpcorner.com/UploadFile/3d39b4/crud-using-the-repository-pattern-in-mvc/ 系列目录: ...
- MVC5+EF6 入门完整教程十一:细说MVC中仓储模式的应用
摘要: 第一阶段1~10篇已经覆盖了MVC开发必要的基本知识. 第二阶段11-20篇将会侧重于专题的讲解,一篇文章解决一个实际问题. 根据园友的反馈, 本篇文章将会先对呼声最高的仓储模式进行讲解. 文 ...
- MVC5+EF6 入门完整教程11--细说MVC中仓储模式的应用
摘要: 第一阶段1~10篇已经覆盖了MVC开发必要的基本知识. 第二阶段11-20篇将会侧重于专题的讲解,一篇文章解决一个实际问题. 根据园友的反馈, 本篇文章将会先对呼声最高的仓储模式进行讲解. 文 ...
随机推荐
- 如何让ChatGPT高效的理解你的Prompt
1.概述 ChatGPT是由 OpenAI 开发的一种强大的语言模型,它在许多自然语言处理任务中展现出了惊人的能力.而其中一个关键的技术概念就是 "Prompt".本文将深入探讨 ...
- C# - ConcurrentDictionary 并发场景使用注意事项
1 自身作为 Enumerable 的遍历 自身作为可遍历对象,键值对为元素进行遍历,是线程安全的,但不提供快照,遍历过程中集合产生变更会直接反馈至此次遍历过程中.但并不一定能够保障获取数据的过程中, ...
- 基于GPT搭建私有知识库聊天机器人(一)实现原理
1.成品演示 支持微信聊天 支持网页聊天 支持微信语音对话 支持私有知识文件训练,并针对文件提问 步骤1:准备本地文件a.txt,支持pdf.txt.markdown.ppt等 步骤2:上传a.txt ...
- Python史上最全种类数据库操作方法,你能想到的数据库类型都在里面!甚至还有云数据库!
本文将详细探讨如何在Python中连接全种类数据库以及实现相应的CRUD(创建,读取,更新,删除)操作.我们将逐一解析连接MySQL,SQL Server,Oracle,PostgreSQL,Mong ...
- 关于DVWA靶场高难度命令执行的代码审计
需要的环境:dvwa 使用的工具:PHP手册 high难度源代码: <?php if( isset( $_POST[ 'Submit' ] ) ) { // Get input $target ...
- 基于Avalonia 11.0.0+ReactiveUI 的跨平台项目开发2-功能开发
基于Avalonia 11.0.0+ReactiveUI 的跨平台项目开发2-功能开发 项目简介:目标是开发一个跨平台的AI聊天和其他功能的客户端平台.目的来学习和了解Avalonia.将这个项目部署 ...
- Maven配置私有仓库
前言 当公司或个人具有自己独有的jar时,不想公开,一般就会放在自己的私有Maven仓库中,在项目中需要引用,此时就需要将公司私有仓库配置到maven当中,一般我们的maven配置的都是aliyu ...
- 五分钟教你使用GitHub寻找优质项目
前言 经常会有同学会问如何使用GitHub找到自己想要的项目,今天咱们就出一期快速入门教程五分钟教你使用GitHub寻找优质项目.GitHub作为世界上最大的项目开源平台之一,上面有着无数优质的开源项 ...
- Linux 概念:存储
块存储 (略) 文件存储 基于文件系统的本地文件存储: 基于网络的共享文件存储:NFS.Samba.Windows文件共享: 基于网络的分布式文件存储:HDFS... 对象存储 一种Key(对象ID) ...
- Cilium系列-15-7层网络CiliumNetworkPolicy简介
系列文章 Cilium 系列文章 前言 今天我们进入 Cilium 安全相关主题, 介绍 CiliumNetworkPolicies 相比于 Kubernetes 网络策略最大的不同: 7 层网络策略 ...