【开源】跨语言·跨平台·跨数据库(6) ——一种ORM缓存的接口实现和容错处理

【开源】跨语言·跨平台·跨数据库(6) ------一种ORM缓存的接口实现和容错处理

2026-07-21

作者:周方勇 / 咏方舟-长江支流(金质打印通、用宝框架开源作者)

用宝框架 · 拥抱第一 · 一次书写 · 三端复用

用宝框架是开源轻量级企业级分层架构基架,也是开放的、可扩展的架构体系 。.NET Standard 2.0,零依赖,支持 MySQL / SQL Server / Oracle / SQLite并可扩展。SQL就是最好的跨平台语言可跨语言无缝迁移至鸿蒙 ArkTS 及 Java 技术栈,接口名、类名、方法签名三端完全一致

用宝架构开发的所有应用,可直接移植到 Java/ArkTS,无需重新设计架构、无需重新分层、无需重新抽象业务逻辑,只需按目标语言语法做形式上的转换。

本文侧重 :接上文一种可插入式缓存接口设计将ICacheProvider接口,用于ORM上。在针对ORM的实体做缓存时,如果使用者忘记这个强大的功能没有应用DI,依赖注入没有怎么办?这里提供了几种方式及容错处理。



ORM缓存基类

缓存基类,采用继承框架IEntity接口的针对实体映射的IMapEntity接口,体现了面向对象基于接口编程的方法。

csharp 复制代码
using System;
using System.IO;
using UserBaoTech.Foundation.Data;
using UserBaoTech.Foundation.Entities;
using UserBaoTech.Foundation.Infrastructure;
using UserBaoTech.Foundation.UbException;

namespace UserBaoTech.Foundation.ORM.Cache
{
    /// <summary>
    /// 作者:长流支流 2026-07-21
    /// 实体缓存管理器基类 ------ 提供模板缓存、刷新、文件变更检测能力
    /// 缓存直接存储 TEntity 类型,避免类型转换
    /// </summary>
    /// <typeparam name="TEntity">实体类型,必须实现 IMapEntity&lt;string&gt;</typeparam>
    public abstract class EntityCacheManager<TEntity>
        where TEntity : IMapEntity<string>
    {
        private readonly string _contentRootPath;
        private readonly ICacheProvider _cacheProvider;
        private const string CACHE_KEY_PREFIX = "EntityCache_";

        protected EntityCacheManager(string contentRootPath, ICacheProvider cacheProvider)
        {
            _contentRootPath = contentRootPath;
            _cacheProvider = cacheProvider ?? new NullCacheProvider();
        }

        protected string ContentRootPath
        {
            get { return _contentRootPath; }
        }

        protected ICacheProvider CacheProvider
        {
            get { return _cacheProvider; }
        }

        private string GetCacheKey(string name)
        {
            return CACHE_KEY_PREFIX + name;
        }

        /// <summary>
        /// 获取或加载缓存
        /// </summary>
        public TEntity GetOrLoad(string name)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw new UserBaoException("缓存名称不能为空", "CACHE_KEY_EMPTY");
            }

            string cacheKey = this.GetCacheKey(name);

            // 1. 检查缓存是否存在
            if (_cacheProvider.Exists(cacheKey))
            {
                TEntity cached = _cacheProvider.Get<TEntity>(cacheKey);
                if (cached != null)
                {
                    // 检查文件是否变更
                    string filePath = this.GetFilePath(name);
                    if (File.Exists(filePath))
                    {
                        DateTime currentFileTime = File.GetLastWriteTime(filePath);
                        DateTime cachedFileTime = this.GetFileTimeFromEntity(cached);
                        if (currentFileTime > cachedFileTime)
                        {
                            // 文件已变更,重新加载
                            return this.LoadAndCache(name);
                        }
                    }
                    return cached;
                }
            }

            // 2. 缓存未命中或文件已变更,重新加载
            return this.LoadAndCache(name);
        }

        /// <summary>
        /// 加载并缓存
        /// </summary>
        private TEntity LoadAndCache(string name)
        {
            string filePath = this.GetFilePath(name);

            if (!File.Exists(filePath))
            {
                throw new UserBaoException(
                    "配置文件不存在:" + filePath,
                    "CONFIG_NOT_FOUND"
                );
            }

            // 由子类实现具体的加载逻辑
            TEntity entity = this.LoadFromFile(filePath);

            // 将文件修改时间存入实体(由子类重写)
            DateTime lastWrite = File.GetLastWriteTime(filePath);
            this.SetFileTimeToEntity(entity, lastWrite);

            // 存入缓存
            string cacheKey = this.GetCacheKey(name);
            _cacheProvider.Set(cacheKey, entity);

            return entity;
        }

        /// <summary>
        /// 子类实现:从文件加载实体
        /// </summary>
        protected abstract TEntity LoadFromFile(string filePath);

        /// <summary>
        /// 从实体中获取文件修改时间(子类可重写)
        /// </summary>
        protected virtual DateTime GetFileTimeFromEntity(TEntity entity)
        {
            // 默认返回最小值,由子类根据具体实体类型重写
            return DateTime.MinValue;
        }

        /// <summary>
        /// 将文件修改时间存入实体(子类可重写)
        /// </summary>
        protected virtual void SetFileTimeToEntity(TEntity entity, DateTime fileTime)
        {
            // 默认不做任何事,由子类重写
        }

        /// <summary>
        /// 获取文件路径(子类可重写)
        /// </summary>
        protected virtual string GetFilePath(string name)
        {
            // 默认:ContentRootPath + "/Configs/" + name + ".xml"
            string relativePath = name.Replace('/', Path.DirectorySeparatorChar);
            return Path.Combine(_contentRootPath, "Configs", relativePath + ".xml");
        }

        /// <summary>
        /// 刷新指定缓存
        /// </summary>
        public void Refresh(string name, bool loadImmediately = false)
        {
            if (string.IsNullOrEmpty(name))
            {
                this.RefreshAll(loadImmediately);
                return;
            }

            string cacheKey = this.GetCacheKey(name);
            _cacheProvider.Remove(cacheKey);

            if (loadImmediately)
            {
                this.LoadAndCache(name);
            }
        }

        /// <summary>
        /// 刷新所有缓存
        /// </summary>
        public void RefreshAll(bool loadImmediately = false)
        {
            _cacheProvider.Clear();

            if (loadImmediately)
            {
                // 由于 ICacheProvider.Clear() 清空了所有缓存,
                // 但无法枚举所有 key,由调用方自行逐个刷新
                // 此处仅保留方法签名兼容
            }
        }

        /// <summary>
        /// 检查缓存是否存在
        /// </summary>
        public bool Exists(string name)
        {
            string cacheKey = this.GetCacheKey(name);
            return _cacheProvider.Exists(cacheKey);
        }

        /// <summary>
        /// 获取缓存项(不触发加载)
        /// </summary>
        public TEntity Get(string name)
        {
            string cacheKey = this.GetCacheKey(name);
            if (_cacheProvider.Exists(cacheKey))
            {
                return _cacheProvider.Get<TEntity>(cacheKey);
            }
            return default(TEntity);
        }
    }
}

架构闭环

您的想法方向正确,但需要更精细的设计。直接去掉 abstract 并让 LoadFromFile 返回 null,会破坏 GetOrLoad 的健壮性------它会在 LoadAndCache 中拿到 null 并试图存缓存,导致空引用异常。


EntityCacheManager抽象/实例类方案

在这种,采用一一种叫模式方法的设计模式,在LoadAndCache(string name)方法中调用 this.LoadFromFile(filePath);是为了更好的对有扩展需求的设计,有的灵活配置在文件中。面向对象核心是抽象、重载、多态。

因此,将EntityCacheManager设计为抽象类,LoadFromFile()设计为抽象方法,意味着EntityCacheManager不能直接实例化,即不能new EntityCacheManager(),那么子类必须实现LoadFromFile()方法。

方案一:将 EntityCacheManager 拆分为两个独立类

1. 抽象基类(保留现有设计,用于 ORM写死的实体如Products实体类、AnyORM 等动态实体)

csharp 复制代码
public abstract class EntityCacheManager<TEntity>
    where TEntity : IMapEntity<string>
{
    // 现有全部代码保持不变
    protected abstract TEntity LoadFromFile(string filePath);
    // ...
}

2. 新增具体实现类(用于静态实体)

csharp 复制代码
public class StaticEntityCacheManager<TEntity> : EntityCacheManager<TEntity>
    where TEntity : IMapEntity<string>, new()
{
    private readonly Func<string, TEntity> _loader;  // 由调用方传入加载逻辑

    public StaticEntityCacheManager(
        string contentRootPath,
        ICacheProvider cacheProvider,
        Func<string, TEntity> loader)
        : base(contentRootPath, cacheProvider)
    {
        _loader = loader;
    }

    protected override TEntity LoadFromFile(string filePath)
    {
        // 静态实体不需要从文件加载,直接返回新实例(或由调用方决定)
        // 如果确实需要从文件加载,可以用 _loader(filePath)
        return new TEntity();
    }
}

方案二:将 LoadFromFile 改为虚方法(非抽象)

csharp 复制代码
public class EntityCacheManager<TEntity>
    where TEntity : IMapEntity<string>
{
    // 改为虚方法,默认实现返回 null(但调用方需判断)
    protected virtual TEntity LoadFromFile(string filePath)
    {
        return default(TEntity);
    }

    private TEntity LoadAndCache(string name)
    {
        string filePath = GetFilePath(name);
        // ...
        TEntity entity = LoadFromFile(filePath);
        if (entity == null)
        {
            // 静态实体可在此处创建默认实例
            entity = Activator.CreateInstance<TEntity>();
        }
        // ...
    }
}

这样静态实体继承时不需要实现 LoadFromFile,但需要在 LoadAndCache 中处理 null 分支。


方案三(推荐):独立出"实体工厂"接口

将"如何获取实体"抽象为独立接口,缓存管理器依赖此接口,而非自身实现加载逻辑。

csharp 复制代码
public interface IEntityLoader<TEntity>
    where TEntity : IMapEntity<string>
{
    TEntity Load(string identifier);  // identifier 可以是文件路径或名称
}

public class EntityCacheManager<TEntity>
    where TEntity : IMapEntity<string>
{
    private readonly IEntityLoader<TEntity> _loader;

    public EntityCacheManager(
        string contentRootPath,
        ICacheProvider cacheProvider,
        IEntityLoader<TEntity> loader)
    {
        // ...
        _loader = loader;
    }

    private TEntity LoadAndCache(string name)
    {
        // ...
        TEntity entity = _loader.Load(filePath);
        // ...
    }
}

这样:

  • AnyORM :提供 XEntityLoader(解析 配置)
  • 静态实体 :提供 StaticEntityLoaderreturn new TEntity()
  • 完全解耦,无需修改基类

您倾向哪种方案?

  • 方案一:保留抽象基类,新增静态实体专用派生类。
  • 方案二:将抽象方法改为虚方法,默认返回默认值。
  • 方案三 :引入 IEntityLoader<T> 接口,彻底解耦。

如果你让AI来选,AI估计 选方案二,AI生成代码就喜欢一步到位完成功能,不考虑灵活复用性,但主技术控来选,很可能建议方案三,因为它最灵活且符合开闭原则。读者有什么想法?

我说,方案二,耦合性太大,方案三是过度设计,我们搞ORM,会只做动态、静态实体,用方案一抽象基类派生最合适。


用宝开源ORM是必须用DI吗?

前面说了,应用程序启动时,提供一个 builder.Services.AddSingleton<ICacheProvider, NullCacheProvider>(); 注册,以防止报错。因为我们继承EntityCacheManager的时候,要注入ICacheProvider 的接口实例,此时一个小技巧是发现使用者没有DI注册,这时,在构造函数注入的时候做一个判断,以便引入一个默认什么也没有做的实例new NullCacheProvider()。

csharp 复制代码
    /// <summary>
    /// XML 实体缓存管理器 ------ 继承 EntityCacheManager,专用于 XmlMapEntity
    /// 支持外部 ICacheProvider 和内部后备缓存(内存字典)双机制
    /// </summary>
    public class XmlEntityCacheManager : EntityCacheManager<XmlMapEntity>
    {
        private readonly XmlEntityParser _parser;
        private readonly IDataDictionary<string, XmlMapEntity> _fallbackCache;

        public XmlEntityCacheManager(
            string contentRootPath,
            ICacheProvider cacheProvider,
            XmlEntityParser parser)
            : base(contentRootPath, cacheProvider ?? new NullCacheProvider())
        {
            _parser = parser ?? throw new ArgumentNullException(nameof(parser));
            _fallbackCache = new DataDictionary<string, XmlMapEntity>();
        }
    }    

架构闭环

复制代码
用户请求
    ↓
EntityCacheManager.GetOrLoad()
    ↓
外部 ICacheProvider 存在且有效?
    ├── 是 → Redis/MemoryCache(分布式、高可用、可观测)
    └── 否 → 内部内存字典(零配置、单机、保运行)
    ↓
返回模板 → 业务处理

使用者没依赖注入

上面说了使用都根本以为你这ORM是个最基本的东西,根据没相到程序启动时要注册? 但是你用new NullCacheProvider()其实什么也没做,内部怎么处理,其实外部没注册可以用 *内部内存字典(_fallbackCache

  • 真正的缓存实现(ICacheProvider 的核心差异:
维度 内部内存字典(Fallback) 真正的缓存实现(ICacheProvider)
过期策略(TTL) ❌ 无。永久驻留,直到手动 Refresh 或重启应用。 ✅ 支持。Set<T> 可指定 TimeSpan 绝对/滑动过期,自动失效。
内存管理 ❌ 无。字典会无限增长(只增不减),可能造成内存泄漏。 ✅ 有。如 MemoryCache 会按内存压力自动驱逐冷数据,Redis 有 LRU 策略。
跨实例共享 ❌ 仅限当前进程。多服务器部署时各存各的,浪费内存且不一致。 ✅ 可共享。如 Redis 支持分布式,多服务器共用一份缓存。
持久化 ❌ 进程重启即丢失。 ✅ 可持久化。Redis 支持 AOF/RDB,重启不丢失。
序列化 ❌ 直接存对象引用,无需序列化(快速但耦合)。 ✅ 可支持跨进程序列化(如 JSON/ProtoBuf),适用于分布式。
监控/统计 ❌ 无。 ✅ 可对接监控系统(命中率、内存占用等)。
适用场景 快速验证、单机部署、开发调试、容错兜底。 生产环境、高并发、分布式集群、需要精细控制缓存策略。

设计结论

_fallbackCache 的定位是"生存保障"

  • 用户不配缓存 → 能跑。
  • 用户缓存出问题 → 能跑。
  • 单机小应用 → 够用。

ICacheProvider 的定位是"性能与扩展"

  • 分布式多实例 → 共享缓存,减少重复解析。
  • 高并发 → 缓存失效策略可控。
  • 生产环境 → 可观测、可调优。

当前代码是"先外部,后内部"的双层容错

复制代码
用户请求 → GetOrLoad()
    ↓
外部 ICacheProvider 是否可用(非 NullCacheProvider)?
    ├── 是 → 使用外部缓存(高性能、分布式、可控)
    └── 否 → 自动降级到内部内存字典(零配置、无感知、保运行)

这样设计,既保证了"零配置开箱即用",又为高级用户保留了"可插拔高性能缓存"的扩展能力。 符合框架"轻量、易用、不强制依赖"的定位。


欢迎拷贝、转载,无需授权

反馈与交流 :欢迎在评论区留言或私信交流。如果你正在寻找一套 不用 EF、不用 Dapper、可跨语言迁移 的轻量级基架,用宝框架或许是一个值得尝试的选择。


用宝框架,拥抱第一 · 一次书写 · 三端复用------不仅是用户的朋友,而且是用户的宝贝

相关推荐
努力进修1 小时前
破除工业 AI 业务落地壁垒:多模时序融合架构重塑设备全维度数据价值
数据库·人工智能·架构
静水楼台x1 小时前
spring security
java·数据库·spring
深度研习笔记2 小时前
OpenCV工业视觉进阶14|SQLite违规数据库存储+历史记录查询+Excel报表导出,完成项目商用数据闭环(验收必备)
数据库·opencv·sqlite
要开心吖ZSH4 小时前
一文搞懂:JDK 21 虚拟线程 vs N种异步方案,到底该怎么选?
java·数据库·jdk·虚拟线程
guodingdingh9 小时前
软件开发工作问题总结0718
java·开发语言·数据库
GuWenyue10 小时前
Cursor黑盒拆解!1套LangChain.js手写Mini编程Agent,自动生成React项目,效率提升60%
前端·数据库·人工智能
Miao1213112 小时前
某海外住宿平台如何在大规模场景下实现指标一致性:Minerva 指标平台实践
大数据·数据库·人工智能
冬奇Lab12 小时前
每日一个开源项目(第164篇):毕昇(BISHENG)- 面向企业的开源 LLM DevOps 平台
人工智能·开源·agent
CodexDave12 小时前
MySQL事务隔离级别与MVCC机制解析
前端·数据库·mysql·nginx·性能优化·负载均衡