using Infrastructure.Attribute; using MDM.Model.Plant; using MDM.Services.IPlantService; using System.Collections.Concurrent; using System.Collections.Generic; namespace MDM.Services.Plant { /// /// 用于缓存 PlantPlcIoPoint 数据的服务 /// [AppService(ServiceType = typeof(PlcIoPointCacheService), ServiceLifetime = LifeTime.Singleton)] public class PlcIoPointCacheService { // 使用线程安全的字典缓存所有点位,Key 是点位 ID private readonly ConcurrentDictionary _pointsById = new(); /// /// 初始化缓存(由 IHostedService 调用) /// /// 从数据库加载的点位集合 public void InitializeCache(IEnumerable points) { if (points == null) return; // 清空旧数据 _pointsById.Clear(); // 只缓存有效的点位(IsActive == 1) foreach (var point in points.Where(p => p.IsActive == 1)) { if (point.Id > 0) { _pointsById[point.Id] = point; } } } /// /// 根据 ID 获取点位 /// /// 点位 ID /// 点位对象,如果不存在返回 null public PlantPlcIoPoint? GetPointById(int id) { _pointsById.TryGetValue(id, out var point); return point; } /// /// 获取所有已缓存的点位 /// public IEnumerable GetAllCachedPoints() { return _pointsById.Values; } // 可根据需要添加更多方法,如: // - 按 工站 + 设备 分组查询 // - 按 点位类型、工艺参数等过滤 } }