SqlSugar仓储类及其二级缓存

1、引入nuget包

		install-package sqlSugar 

2、仓储类

 public class BaseRepository<TEntity> : SimpleClient<TEntity> where TEntity : class, new()
    {
        private Logger loggers = Logger.CreateLogger(typeof(BaseRepository<TEntity>));
        public BaseRepository(ISqlSugarClient context = null) : base(context)
        {
            if (context == null)
            {
                // 分库处理
                Config config = Config.getBean();
                if (typeof(TEntity).GetTypeInfo().GetCustomAttributes(typeof(SugarTable), true).FirstOrDefault((x => x.GetType() == typeof(SugarTable))) is SugarTable sugarTable)
                {
                    string conncent = sugarTable.TableDescription;
                    if (string.IsNullOrWhiteSpace(conncent))  { config = Config.getBean();}
                    else{ config = Config.getBean(conncent.ToUpper());}
                }

                base.Context = new SqlSugarClient(new ConnectionConfig()
                {
                    DbType = (DbType)config.DbType,
                    InitKeyType = (InitKeyType)config.InitKeyType,
                    IsAutoCloseConnection = config.IsAutoCloseConnection,
                    ConnectionString = config.ConnectionString,
                    ConfigureExternalServices = new ConfigureExternalServices()
                    {
                        DataInfoCacheService = new HttpRuntimeCache()
                    }
                });
                base.Context.Aop.OnLogExecuting = (sql, pars) => //SQL执行中事件
                { //loggers.Warn(new LogContent("OnLogExecuting", "SQL语句打印", "SQL:" + GetParas(pars) + "【SQL语句】:" + sql));
                };
                base.Context.Aop.OnError = (e) =>{
                    loggers.Error(new LogContent("BaseRepository", "SQL异常事件", e.Message));
                };
            }
        }



        private string GetParas(SugarParameter[] pars)
        {
            string key = "【SQL参数】:";
            foreach (var param in pars)
            {
                key += $"{param.ParameterName}:{param.Value}\n";
            }

            return key;
        }
        
        internal ISqlSugarClient Db
        {
            get { return Context; }
        }
        
        public void BeginTran()
        {
            Context.Ado.BeginTran();
        }

        public void Commit()
        {
            Context.Ado.CommitTran();
        }

        public void Rollback()
        {
            Context.Ado.RollbackTran();
        }
        /// <summary>
        /// 功能描述:根据ID查新数据
        /// </summary>
        /// <param name="objId">id(必须指定主键特性 [SugarColumn(IsPrimaryKey=true)]),如果是联合主键,请使用Where条件</param>
        /// <returns></returns>
        public async Task<TEntity> QueryById(object objId)
        {
            return await Context.Queryable<TEntity>().In(objId).SingleAsync();
        }
        /// <summary>
        /// 功能描述:根据ID查询一条数据
        /// </summary>
        /// <param name="objId">id(必须指定主键特性 [SugarColumn(IsPrimaryKey=true)]),如果是联合主键,请使用Where条件</param>
        /// <param name="blnUseCache">是否使用缓存</param>
        /// <returns>数据实体</returns>
        public async Task<TEntity> QueryById(object objId, bool blnUseCache = false)
        {
            return await Context.Queryable<TEntity>().WithCacheIF(blnUseCache).In(objId).SingleAsync();
        }
        /// <summary>
        /// 功能描述:根据ID查询数据
        /// </summary>
        /// <param name="lstIds">id列表(必须指定主键特性 [SugarColumn(IsPrimaryKey=true)]),如果是联合主键,请使用Where条件</param>
        /// <returns>数据实体列表</returns>
        public async Task<List<TEntity>> QueryByIDs(object[] lstIds)
        {
            return await Context.Queryable<TEntity>().In(lstIds).ToListAsync();
        }

        /// <summary>
        /// 写入实体数据
        /// </summary>
        /// <param name="entity">实体类</param>
        /// <returns></returns>
        public async Task<long> Add(TEntity entity)
        {
            var insert = Context.Insertable(entity);
            return await insert.ExecuteReturnBigIdentityAsync();
        }

        /// <summary>
        /// 写入实体数据(同步方法)
        /// </summary>
        /// <param name="entity">实体类</param>
        /// <returns></returns>
        public long AddSync(TEntity entity)
        {
            var insert = Context.Insertable(entity);
            return insert.ExecuteReturnBigIdentity();
        }


        /// <summary>
        /// 写入实体数据
        /// </summary>
        /// <param name="entity">实体类</param>
        /// <param name="insertColumns">指定只插入列</param>
        /// <returns>返回自增量列</returns>
        public async Task<int> Add(TEntity entity, Expression<Func<TEntity, object>> insertColumns = null)
        {
            var insert = Context.Insertable(entity);
            if (insertColumns == null)
            {
                return await insert.ExecuteReturnIdentityAsync();
            }
            else
            {
                return await insert.InsertColumns(insertColumns).ExecuteReturnIdentityAsync();
            }
        }

        /// <summary>
        /// 写入实体数据
        /// </summary>
        /// <param name="entity">实体类</param>
        /// <returns>返回被影响的行数</returns>
        public async Task<int> AddByRows(TEntity entity)
        {
            var insert = Context.Insertable(entity);
            return await insert.ExecuteCommandAsync();
        }
        /// <summary>
        /// 写入实体数据
        /// </summary>
        /// <param name="listEntity">实体类集合</param>
        /// <returns>返回被影响的行数</returns>
        public int AddByRows(List<TEntity> listEntity)
        {
            return Context.Insertable(listEntity.ToArray()).ExecuteCommand();
        }

        /// <summary>
        /// 批量插入实体(速度快)
        /// </summary>
        /// <param name="listEntity">实体集合</param>
        /// <returns>影响行数</returns>
        public async Task<int> Add(List<TEntity> listEntity)
        {
            return await Context.Insertable(listEntity.ToArray()).ExecuteCommandAsync();
        }

        public int AddSync(List<TEntity> listEntity)
        {
            return Context.Insertable(listEntity.ToArray()).ExecuteCommand();
        }


        /// <summary>
        /// 更新实体数据
        /// </summary>
        /// <param name="entity">实体类</param>
        /// <returns></returns>
        public async Task<bool> Update(TEntity entity)
        {
            //这种方式会以主键为条件
            return await Context.Updateable(entity).ExecuteCommandHasChangeAsync();
        }
        public bool Update(List<TEntity> entities)
        {
            return Context.Updateable(entities).ExecuteCommandHasChange();
        }
        /// <summary>
        /// 同步 更新
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public int UpdateSync(TEntity entity)
        {
            //这种方式会以主键为条件
            return Context.Updateable(entity).ExecuteCommand();
        }
        /// <summary>
        /// 同步 更新批量
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public int UpdateSync(List<TEntity> entities)
        {
            return Context.Updateable(entities).ExecuteCommand();
        }



        /// <summary>
        /// 异步 更新实体
        /// </summary>
        /// <param name="entities"></param>
        /// <returns></returns>
        public async Task<int> UpdateAsync(List<TEntity> entities)
        {

            return await Context.Updateable(entities).ExecuteCommandAsync();

        }

        public async Task<bool> Update(TEntity entity, string strWhere)
        {
            return await Context.Updateable(entity).Where(strWhere).ExecuteCommandHasChangeAsync();
        }

        public async Task<bool> Update(string strSql, SugarParameter[] parameters = null)
        {
            return await Context.Ado.ExecuteCommandAsync(strSql, parameters) > 0;
        }

        public async Task<bool> Update(object operateAnonymousObjects)
        {
            return await Context.Updateable<TEntity>(operateAnonymousObjects).ExecuteCommandAsync() > 0;
        }

        public async Task<bool> Update(
          TEntity entity,
          List<string> lstColumns = null,
          List<string> lstIgnoreColumns = null,
          string strWhere = ""
            )
        {
            IUpdateable<TEntity> up = Context.Updateable(entity);
            if (lstIgnoreColumns != null && lstIgnoreColumns.Count > 0)
            {
                up = up.IgnoreColumns(lstIgnoreColumns.ToArray());
            }
            if (lstColumns != null && lstColumns.Count > 0)
            {
                up = up.UpdateColumns(lstColumns.ToArray());
            }
            if (!string.IsNullOrEmpty(strWhere))
            {
                up = up.Where(strWhere);
            }
            return await up.ExecuteCommandHasChangeAsync();
        }

        /// <summary>
        /// 根据实体删除一条数据
        /// </summary>
        /// <param name="entity">实体类</param>
        /// <returns></returns>
        public async Task<bool> Delete(TEntity entity)
        {
            return await Context.Deleteable(entity).ExecuteCommandHasChangeAsync();
        }

        /// <summary>
        /// 删除指定ID的数据
        /// </summary>
        /// <param name="id">主键ID</param>
        /// <returns></returns>
        public async Task<bool> DeleteById(object id)
        {
            return await Context.Deleteable<TEntity>(id).ExecuteCommandHasChangeAsync();
        }

        /// <summary>
        /// 删除指定ID集合的数据(批量删除)
        /// </summary>
        /// <param name="ids">主键ID集合</param>
        /// <returns></returns>
        public async Task<bool> DeleteByIds(object[] ids)
        {
            return await Context.Deleteable<TEntity>().In(ids).ExecuteCommandHasChangeAsync();
        }



        /// <summary>
        /// 功能描述:查询所有数据
        /// </summary>
        /// <returns>数据列表</returns>
        public async Task<List<TEntity>> Query()
        {
            return await Context.Queryable<TEntity>().ToListAsync();
        }

        /// <summary>
        /// 功能描述:查询数据列表
        /// </summary>
        /// <param name="strWhere">条件</param>
        /// <returns>数据列表</returns>
        public async Task<List<TEntity>> Query(string strWhere)
        {
            return await Context.Queryable<TEntity>().WhereIF(!string.IsNullOrEmpty(strWhere), strWhere).ToListAsync();
        }

        /// <summary>
        /// 功能描述:查询数据列表
        /// </summary>
        /// <param name="whereExpression">whereExpression</param>
        /// <returns>数据列表</returns>
        public async Task<List<TEntity>> Query(Expression<Func<TEntity, bool>> whereExpression)
        {
            return await Context.Queryable<TEntity>().WhereIF(whereExpression != null, whereExpression).ToListAsync();
        }
        public async Task<TEntity> QueryFist(Expression<Func<TEntity, bool>> whereExpression)
        {
            return await Context.Queryable<TEntity>().WhereIF(whereExpression != null, whereExpression).FirstAsync();
        }

        /// <summary>
        /// 功能描述:查询一个列表
        /// </summary>
        /// <param name="whereExpression">条件表达式</param>
        /// <param name="strOrderByFileds">排序字段,如name asc,age desc</param>
        /// <returns>数据列表</returns>
        public async Task<List<TEntity>> Query(Expression<Func<TEntity, bool>> whereExpression, string strOrderByFileds)
        {
            return await Context.Queryable<TEntity>().WhereIF(whereExpression != null, whereExpression).OrderByIF(strOrderByFileds != null, strOrderByFileds).ToListAsync();
        }
        /// <summary>
        /// 功能描述:查询一个列表
        /// </summary>
        /// <param name="whereExpression"></param>
        /// <param name="orderByExpression"></param>
        /// <param name="isAsc"></param>
        /// <returns></returns>
        public async Task<List<TEntity>> Query(Expression<Func<TEntity, bool>> whereExpression, Expression<Func<TEntity, object>> orderByExpression, bool isAsc = true)
        {
            return await Context.Queryable<TEntity>().OrderByIF(orderByExpression != null, orderByExpression, isAsc ? OrderByType.Asc : OrderByType.Desc).WhereIF(whereExpression != null, whereExpression).ToListAsync();
        }

        /// <summary>
        /// 功能描述:查询一个列表
        /// </summary>
        /// <param name="strWhere">条件</param>
        /// <param name="strOrderByFileds">排序字段,如name asc,age desc</param>
        /// <returns>数据列表</returns>
        public async Task<List<TEntity>> Query(string strWhere, string strOrderByFileds)
        {
            return await Context.Queryable<TEntity>().OrderByIF(!string.IsNullOrEmpty(strOrderByFileds), strOrderByFileds).WhereIF(!string.IsNullOrEmpty(strWhere), strWhere).ToListAsync();
        }


        /// <summary>
        /// 功能描述:查询前N条数据
        /// </summary>
        /// <param name="whereExpression">条件表达式</param>
        /// <param name="intTop">前N条</param>
        /// <param name="strOrderByFileds">排序字段,如name asc,age desc</param>
        /// <returns>数据列表</returns>
        public async Task<List<TEntity>> Query(
            Expression<Func<TEntity, bool>> whereExpression,
            int intTop,
            string strOrderByFileds)
        {
            return await Context.Queryable<TEntity>().OrderByIF(!string.IsNullOrEmpty(strOrderByFileds), strOrderByFileds).WhereIF(whereExpression != null, whereExpression).Take(intTop).ToListAsync();
        }

        /// <summary>
        /// 功能描述:查询前N条数据
        /// </summary>
        /// <param name="strWhere">条件</param>
        /// <param name="intTop">前N条</param>
        /// <param name="strOrderByFileds">排序字段,如name asc,age desc</param>
        /// <returns>数据列表</returns>
        public async Task<List<TEntity>> Query(
            string strWhere,
            int intTop,
            string strOrderByFileds)
        {
            return await Context.Queryable<TEntity>().OrderByIF(!string.IsNullOrEmpty(strOrderByFileds), strOrderByFileds).WhereIF(!string.IsNullOrEmpty(strWhere), strWhere).Take(intTop).ToListAsync();
        }



        /// <summary>
        /// 功能描述:分页查询
        /// </summary>
        /// <param name="whereExpression">条件表达式</param>
        /// <param name="intPageIndex">页码(下标0)</param>
        /// <param name="intPageSize">页大小</param>
        /// <param name="intTotalCount">数据总量</param>
        /// <param name="strOrderByFileds">排序字段,如name asc,age desc</param>
        /// <returns>数据列表</returns>
        public async Task<List<TEntity>> Query(
            Expression<Func<TEntity, bool>> whereExpression,
            int intPageIndex,
            int intPageSize,
            string strOrderByFileds)
        {
            return await Context.Queryable<TEntity>().OrderByIF(!string.IsNullOrEmpty(strOrderByFileds), strOrderByFileds).WhereIF(whereExpression != null, whereExpression).ToPageListAsync(intPageIndex, intPageSize);
        }

        /// <summary>
        /// 功能描述:分页查询
        /// </summary>
        /// <param name="strWhere">条件</param>
        /// <param name="intPageIndex">页码(下标0)</param>
        /// <param name="intPageSize">页大小</param>
        /// <param name="intTotalCount">数据总量</param>
        /// <param name="strOrderByFileds">排序字段,如name asc,age desc</param>
        /// <returns>数据列表</returns>
        public async Task<List<TEntity>> Query(
          string strWhere,
          int intPageIndex,
          int intPageSize,

          string strOrderByFileds)
        {

            return await Context.Queryable<TEntity>().OrderByIF(!string.IsNullOrEmpty(strOrderByFileds), strOrderByFileds).WhereIF(!string.IsNullOrEmpty(strWhere), strWhere).ToPageListAsync(intPageIndex, intPageSize);
        }




        /// <summary> 
        ///查询-多表查询
        /// </summary> 
        /// <typeparam name="T">实体1</typeparam> 
        /// <typeparam name="T2">实体2</typeparam> 
        /// <typeparam name="T3">实体3</typeparam>
        /// <typeparam name="TResult">返回对象</typeparam>
        /// <param name="joinExpression">关联表达式 (join1,join2) => new object[] {JoinType.Left,join1.UserNo==join2.UserNo}</param> 
        /// <param name="selectExpression">返回表达式 (s1, s2) => new { Id =s1.UserNo, Id1 = s2.UserNo}</param>
        /// <param name="whereLambda">查询表达式 (w1, w2) =>w1.UserNo == "")</param> 
        /// <returns>值</returns>
        public async Task<List<TResult>> QueryMuch<T, T2, T3, TResult>(
            Expression<Func<T, T2, T3, object[]>> joinExpression,
            Expression<Func<T, T2, T3, TResult>> selectExpression,
            Expression<Func<T, T2, T3, bool>> whereLambda = null) where T : class, new()
        {
            if (whereLambda == null)
            {
                return await Context.Queryable(joinExpression).Select(selectExpression).ToListAsync();
            }
            return await Context.Queryable(joinExpression).Where(whereLambda).Select(selectExpression).ToListAsync();
        }

        /// <summary>
        /// 根据Sql查询集合
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public async Task<List<TEntity>> QuerySql(string sql)
        {
            return await Context.SqlQueryable<TEntity>(sql).ToListAsync();
        }





        /// <summary>
        /// ADO 查询
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public async Task<List<TEntity>> SqlQueryTolist(string sql)
        {
            return await Context.Ado.SqlQueryAsync<TEntity>(sql);
        }
        /// <summary>
        /// ADO 查询
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public async Task<List<T>> SqlQueryTolist<T>(string sql)
        {
            return await Context.Ado.SqlQueryAsync<T>(sql);
        }


        /// <summary>
        /// ADO 查询
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public async Task<TEntity> SqlQuery(string sql)
        {
            return await Context.Ado.SqlQuerySingleAsync<TEntity>(sql);
        }
        /// <summary>
        /// ADO 查询
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="pairs"></param>
        /// <returns></returns>
        public async Task<T> SqlQuery<T>(string sql)
        {
            return await Context.Ado.SqlQuerySingleAsync<T>(sql);
        }

        /// <summary>
        /// 查询返回 集合
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="sql"></param>
        /// <returns>返回List 集合</returns>
        public async Task<List<T>> SqlQuerys<T>(string sql)
        {
            return await Context.Ado.SqlQueryAsync<T>(sql);
        }

        /// <summary>
        /// ADO 查询
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="pairs"></param>
        /// <returns>返回List 集合</returns>
        public async Task<List<T>> SqlQuery<T>(string sql, Dictionary<string, object> pairs)
        {
            return await Context.Ado.SqlQueryAsync<T>(sql, FormationParameter(pairs).ToArray());
        }
        /// <summary>
        /// ADO 查询
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="pairs"></param>
        /// <returns>返回List 集合</returns>
        public async Task<List<TEntity>> SqlQuery(string sql, Dictionary<string, object> pairs)
        {
            return await Context.Ado.SqlQueryAsync<TEntity>(sql, FormationParameter(pairs).ToArray());
        }

        /// <summary>
        /// ADO 执行 增删改方法
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public async Task<int> ExecuteCommand(string sql)
        {
            return await Context.Ado.ExecuteCommandAsync(sql);
        }



        /// <summary>
        /// ADO 执行 增删改方法
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="pairs"></param>
        /// <returns></returns>
        public async Task<int> ExecuteCommand(string sql, Dictionary<string, object> pairs)
        {
            return await Context.Ado.ExecuteCommandAsync(sql, FormationParameter(pairs).ToArray());
        }




        /// <summary>
        /// 获取序列自增ID
        /// </summary>
        /// <param name="tname">序列名</param>
        /// <param name="sequenceName">对应表名称</param>
        /// <returns></returns>
        public long getquery_id(string sequenceName, string tableName)
        {
            long myvar = 0;
            while (true)
            {
                string sql = "select " + sequenceName + ".NEXTVAL from dual ";
                try
                {
                    myvar = Context.Ado.SqlQuerySingle<long>(sql);

                    if (myvar > 0)
                    {
                        sql = "select count(*) from " + tableName + " where ID=" + myvar.ToString();
                        long myids = Context.Ado.SqlQuerySingle<long>(sql);
                        if (myids == 0)
                        {
                            break;
                        }
                    }
                }
                catch (Exception ex)
                {
                    loggers.Error(new LogContent("getquery_id", "获取序列异常", $"【序列获取失败】:{ex.Message}"));
                }
            }
            return myvar;
        }



        private List<SugarParameter> FormationParameter(Dictionary<string, object> pairs)
        {
            List<SugarParameter> olist = new List<SugarParameter>();
            if (pairs.Count > 0)
            {
                foreach (var item in pairs.Keys)
                {
                    olist.Add(new SugarParameter(item, pairs[item].ToString()));
                }
            }
            return olist;
        }

        /// <summary>
        ///  执行包体 方法(存储过程)
        /// </summary>
        /// <param name="packFuncName">imr_pkg_mr_data_syn.SP_SYN_SYS_USERS</param>
        /// <returns></returns>
        public System.Data.DataTable ExecStoredProcedure(string packFuncName, List<SugarParameter> olist)
        {
            try
            {

                System.Data.DataTable pack = Context.Ado.UseStoredProcedure().GetDataTable(packFuncName, olist.ToArray());
                return pack;
            }
            catch (Exception err)
            {

                throw err;
            }



        }


    }

3、配置文件

{
  "SqlSugarClient": [
    {
      "DbType": "3",
      "Connection": "User Id=TEST;Password=123456;Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=127.0.0.1)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=orcl)));Max Pool Size=512;Pooling=true",
      "InitKeyType":"1"
    }
  ],
  "SqlSugarClient2": [
    {
      "DbType": "3",
      "Connection": "User Id=TEST2;Password=123456;Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=127.0.0.1)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=orcl)));Max Pool Size=512;Pooling=true",
      "InitKeyType":"1"
    }
  ]
}

4、自定义读取json 文件

    public class Config
    {

        /// <summary>
        /// 数据库连接
        /// </summary>
        public string ConnectionString { get; set; }

        /// <summary>
        /// 数据库类型
        /// </summary>
        public int DbType { get; set; }

        /// <summary>
        /// 默认读取实体表方式
        /// </summary>
        public int InitKeyType { get; set; }

        /// <summary>
        /// 是否自动提交事务
        /// </summary>
        public bool IsAutoCloseConnection { get; set; }

        /// <summary>
        /// 获取ConnectionConfig
        /// </summary>
        /// <returns></returns>
        public static Config getBean(string connectName = "SqlSugarClient")
        {
            string path = "";
            if (HttpContext.Current != null)
            {
                path = HttpContext.Current.Server.MapPath("/DbConfig.json");
            }
            else
            {
                path = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "DbConfig.json");
            }
            using (StreamReader r = new StreamReader(path))
            {
                string json = r.ReadToEnd();
                JObject obj = JObject.Parse(json);
                var jToken = obj[$"{connectName}"][0];
                var conf = new Config()
                {
                    DbType = Convert.ToInt32(jToken["DbType"]),
                    ConnectionString = jToken["Connection"].ToString(),
                    InitKeyType = Convert.ToInt32(jToken["InitKeyType"]),
                    IsAutoCloseConnection = true
                };

                return conf;
            }

        }

    }

5、二级缓存类(SqlSugar官网提供)

 /// <summary>
    ///  二级缓存
    /// </summary>
    public class HttpRuntimeCache : ICacheService
    {
        public void Add<V>(string key, V value)
        {
            HttpRuntimeCacheHelper<V>.GetInstance().Add(key, value);
        }

        public void Add<V>(string key, V value, int cacheDurationInSeconds)
        {
            HttpRuntimeCacheHelper<V>.GetInstance().Add(key, value, cacheDurationInSeconds);
        }

        public bool ContainsKey<V>(string key)
        {
            return HttpRuntimeCacheHelper<V>.GetInstance().ContainsKey(key);
        }

        public V Get<V>(string key)
        {
            return HttpRuntimeCacheHelper<V>.GetInstance().Get(key);
        }

        public IEnumerable<string> GetAllKey<V>()
        {
            return HttpRuntimeCacheHelper<V>.GetInstance().GetAllKey();
        }

        public V GetOrCreate<V>(string cacheKey, Func<V> create, int cacheDurationInSeconds = int.MaxValue)
        {
            var cacheManager = HttpRuntimeCacheHelper<V>.GetInstance();
            if (cacheManager.ContainsKey(cacheKey))
            {
                return cacheManager[cacheKey];
            }
            else
            {
                var result = create();
                cacheManager.Add(cacheKey, result, cacheDurationInSeconds);
                return result;
            }
        }

        public void Remove<V>(string key)
        {
            HttpRuntimeCacheHelper<V>.GetInstance().Remove(key);
        }
    }

    internal class HttpRuntimeCacheHelper<V>
    {

        #region 全局变量
        private static HttpRuntimeCacheHelper<V> _instance = null;
        private static readonly object _instanceLock = new object();
        #endregion

        #region 构造函数

        private HttpRuntimeCacheHelper() { }
        #endregion

        #region  属性
        /// <summary>         
        ///根据key获取value     
        /// </summary>         
        /// <value></value>      
        public V this[string key]
        {
            get { return (V)HttpRuntime.Cache[CreateKey(key)]; }
        }
        #endregion

        #region 公共函数

        /// <summary>         
        /// key是否存在       
        /// </summary>         
        /// <param name="key">key</param>         
        /// <returns> ///  存在<c>true</c> 不存在<c>false</c>.        /// /// </returns>         
        public bool ContainsKey(string key)
        {
            return HttpRuntime.Cache[CreateKey(key)] != null;
        }

        /// <summary>         
        /// 获取缓存值         
        /// </summary>         
        /// <param name="key">key</param>         
        /// <returns></returns>         
        public V Get(string key)
        {
            return (V)HttpRuntime.Cache.Get(CreateKey(key));
        }

        /// <summary>         
        /// 获取实例 (单例模式)       
        /// </summary>         
        /// <returns></returns>         
        public static HttpRuntimeCacheHelper<V> GetInstance()
        {
            if (_instance == null)
                lock (_instanceLock)
                    if (_instance == null)
                        _instance = new HttpRuntimeCacheHelper<V>();
            return _instance;
        }

        /// <summary>         
        /// 插入缓存(默认20分钟)        
        /// </summary>         
        /// <param name="key"> key</param>         
        /// <param name="value">value</param>          
        public void Add(string key, V value)
        {
            Add(key, value, 60 * 20);
        }

        /// <summary>         
        /// 插入缓存        
        /// </summary>         
        /// <param name="key"> key</param>         
        /// <param name="value">value</param>         
        /// <param name="cacheDurationInSeconds">过期时间单位秒</param>         
        public void Add(string key, V value, int cacheDurationInSeconds)
        {
            Add(key, value, cacheDurationInSeconds, CacheItemPriority.Default);
        }

        /// <summary>         
        /// 插入缓存.         
        /// </summary>         
        /// <param name="key">key</param>         
        /// <param name="value">value</param>         
        /// <param name="cacheDurationInSeconds">过期时间单位秒</param>         
        /// <param name="priority">缓存项属性</param>         
        public void Add(string key, V value, int cacheDurationInSeconds, CacheItemPriority priority)
        {
            string keyString = CreateKey(key);
            HttpRuntime.Cache.Insert(keyString, value, null,
            DateTime.Now.AddSeconds(cacheDurationInSeconds), Cache.NoSlidingExpiration, priority, null);
        }

        /// <summary>         
        /// 插入缓存.         
        /// </summary>         
        /// <param name="key">key</param>         
        /// <param name="value">value</param>         
        /// <param name="cacheDurationInSeconds">过期时间单位秒</param>         
        /// <param name="priority">缓存项属性</param>         
        public void Add(string key, V value, int
         cacheDurationInSeconds, CacheDependency dependency, CacheItemPriority priority)
        {
            string keyString = CreateKey(key);
            HttpRuntime.Cache.Insert(keyString, value,
             dependency, DateTime.Now.AddSeconds(cacheDurationInSeconds), Cache.NoSlidingExpiration, priority, null);
        }

        /// <summary>         
        /// 删除缓存         
        /// </summary>         
        /// <param name="key">key</param>         
        public void Remove(string key)
        {
            HttpRuntime.Cache.Remove(CreateKey(key));
        }

        /// <summary>
        /// 清除所有缓存
        /// </summary>
        public void RemoveAll()
        {
            System.Web.Caching.Cache cache = HttpRuntime.Cache;
            IDictionaryEnumerator CacheEnum = cache.GetEnumerator();
            ArrayList al = new ArrayList();
            while (CacheEnum.MoveNext())
            {
                al.Add(CacheEnum.Key);
            }
            foreach (string key in al)
            {
                cache.Remove(key);
            }
        }

        /// <summary>
        /// 清除所有包含关键字的缓存
        /// </summary>
        /// <param name="removeKey">关键字</param>
        public void RemoveAll(Func<string, bool> removeExpression)
        {
            System.Web.Caching.Cache _cache = HttpRuntime.Cache;
            var allKeyList = GetAllKey();
            var delKeyList = allKeyList.Where(removeExpression).ToList();
            foreach (var key in delKeyList)
            {
                HttpRuntime.Cache.Remove(key); ;
            }
        }

        /// <summary>
        /// 获取所有缓存key
        /// </summary>
        /// <returns></returns>
        public IEnumerable<string> GetAllKey()
        {
            IDictionaryEnumerator CacheEnum = HttpRuntime.Cache.GetEnumerator();
            while (CacheEnum.MoveNext())
            {
                yield return CacheEnum.Key.ToString();
            }
        }
        #endregion

        #region 私有函数

        /// <summary>         
        ///创建KEY   
        /// </summary>         
        /// <param name="key">Key</param>         
        /// <returns></returns>         
        private string CreateKey(string key)
        {
            return key;
        }
        #endregion
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值