using DirectService.Tools; using JLHHJSvr.BLL; using JLHHJSvr.Com.Model; using LJLib; using LJLib.DAL.SQL; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Data.SqlClient; namespace JLHHJSvr.Helper { internal sealed class CacheHelper : HelperBase { #region 基础资料Mapping /// /// 弹簧资料 /// public class SpringMapping : ICacheMapping { public u_spring GetInstance(SqlCommand cmd, int springid) { var instance = new u_spring() { springid = springid }; DbSqlHelper.SelectOne(cmd, instance, "line_diameter,gram_weight,height,center_diameter,caliber,cyclenum,roll_width,roll_length,arrangement_width,arrangement_height,springtypeid"); return instance; } } /// /// 部门资料 /// public class DeptMapping : ICacheMapping { public u_dept GetInstance(SqlCommand cmd, int deptid) { var instance = new u_dept() { deptid = deptid }; DbSqlHelper.SelectOne(cmd, instance, "pricelistid,profitrate,moneyrate,discount,taxes_rate,managerate,com_profitrate,dannum1_rate,dannum2_rate,dannum3_rate,dannum4_rate"); return instance; } } #endregion #region 获取数据 private static readonly Dictionary _cacheServiceRegistry = new Dictionary(); public TEntity GetData(TKey key) where TEntity: class,new() where TMapping : ICacheMapping, new() { var entityType = typeof(TEntity); if (!_cacheServiceRegistry.TryGetValue(entityType, out var serviceObj)) { var cacheService = new CacheService(new GenericLoader(new TMapping())); _cacheServiceRegistry.Add(entityType, cacheService); serviceObj = cacheService; } var service = (CacheService)serviceObj; return service.Get(cmd,key); } #endregion } #region 核心 public interface ICacheLoader where TValue : class, new() { TValue Load(SqlCommand cmd, TKey key); } public interface ICacheMapping where TValue : class, new() { TValue GetInstance(SqlCommand cmd, TKey key); } public class CacheService where TValue : class, new() { private readonly LJCache _cache; private readonly ICacheLoader _loader; public CacheService(ICacheLoader loader, int cacheMinutes) { _loader = loader; _cache = new LJCache { DefaultAddMinutes = cacheMinutes }; } public CacheService(ICacheLoader loader) { _loader = loader; _cache = new LJCache { DefaultAddMinutes = 120 }; } public TValue Get(SqlCommand cmd,TKey key) { if (!_cache.TryGetValue(key, out TValue value)) { value = _loader.Load(cmd, key); _cache.Add(key, value); } return ObjectHelper.DeepCopy(value); } } public class GenericLoader : ICacheLoader where TValue : class, new() { private readonly ICacheMapping _mapping; public GenericLoader(ICacheMapping mapping) { _mapping = mapping; } public TValue Load(SqlCommand cmd, TKey id) { return _mapping.GetInstance(cmd, id); } } #endregion }