内存数据库的设计与实现(已在大型项目中应用)

一、概况

1、设计总图

      组成,由Redis集群缓存,普通缓存,传统数据库,各类数据驱动

2、内存数据库的增删改查,分页查询

      组成,由数据查询,分页查询,数据存储,数据修改,数据删除

3、内存数据库的驱动

      组成,由驱动适配器,普通缓存驱动,Redis缓存驱动

4、内存数据库与传统数据库的同步(作为安全保障)

      组成,由数据加载到内存,存储同步,修改同步,删除同步,数据容错处理

二、总图

下图,为内存数据库的设计总图

三、内存数据库的查,写,删,改

内存数据的代码实现如下

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;

namespace QPCenterExpress.CoreSafe.CacheBase
{
    public class CacheDataTable
    {
        static CacheService cacheService = new CacheService();
        static int CacheTimeLong = 5;
        static readonly string DBName = (ConfigurationManager.AppSettings["DBName"] == null) ? "HARRYXIA" : ConfigurationManager.AppSettings["DBName"].ToString();
        static readonly string MaxRows = "MaxRows";
        static readonly string MaxDelRows = "MaxDelRows";
        static readonly string KeyField = "KeyField";

        static CacheDataTable()
        {
            //var tempTimeLong = ConfigurationManager.AppSettings["CacheTimeLong"];
            //if (tempTimeLong != null)
            //{
            //    CacheTimeLong = Convert.ToInt32(tempTimeLong);
            //}
        }

        /// <summary>
        /// 增加表的一行到缓存
        /// </summary>
        /// <param name="TableName">表名</param>
        /// <param name="dr">行记录</param>
        /// <param name="fieldKey">主键字段</param>
        /// <param name="longType">缓存时长类型,1:短期,时间为系统配置里的时间,2:长期一年</param>
        /// <returns></returns>
        public static bool AddDataTableToCache(string TableName, DataRow dr, string fieldKey, int longType = 2)
        {
            bool isAdd = false;
            Dictionary<string, string> fieldKeyIndexList = new Dictionary<string, string>();
            Dictionary<string, DataRow> cacheAllSaveGetIndexList = new Dictionary<string, DataRow>();
            try
            {
                int longShortTime = 0;
                if (longType == 2)
                {
                    longShortTime = 350;
                }
                string DataTableRowsKey = DBName + ":" + TableName + ":" + MaxRows;
                string DataTableKey = DBName + ":" + TableName + ":" + "FieldKey";
                string DataTableKeyValue = DBName + ":" + TableName + ":" + fieldKey;
                string addDataTableFieldKey = DBName + ":" + TableName + ":" + fieldKey + ":" + dr[fieldKey];
                string DataTableFieldKeyIndex = DBName + ":" + TableName + ":" + fieldKey + ":" + "Index";
                int row = cacheService.GetCache<int>(DataTableRowsKey);
                string addDataTableKey = "";  
                string DataTableCacheAllSaveGet = DBName + ":" + TableName + ":" + "CacheAllSaveGet"; 
                if (row > 0)
                {
                    row = row + 1;
                    addDataTableKey = DBName + ":" + TableName + ":" + row;
                    fieldKeyIndexList = cacheService.GetCache<Dictionary<string, string>>(DataTableFieldKeyIndex);
                    cacheAllSaveGetIndexList = cacheService.GetCache<Dictionary<string, DataRow>>(DataTableCacheAllSaveGet);
                    if (fieldKeyIndexList == null)
                    {
                        fieldKeyIndexList = new Dictionary<string, string>();
                        cacheAllSaveGetIndexList = new Dictionary<string, DataRow>();
                        fieldKeyIndexList.Add(dr[fieldKey].ToString(), addDataTableKey);
                        cacheAllSaveGetIndexList.Add(dr[fieldKey].ToString(), dr);

                    }
                    else
                    {
                        if (fieldKeyIndexList.ContainsKey(dr[fieldKey].ToString()) == false)
                        {
                            fieldKeyIndexList.Add(dr[fieldKey].ToString(), addDataTableKey);
                            cacheAllSaveGetIndexList.Add(dr[fieldKey].ToString(), dr);
                        }
                        else
                        {
                            fieldKeyIndexList.Remove(dr[fieldKey].ToString());
                            fieldKeyIndexList.Add(dr[fieldKey].ToString(), addDataTableKey);
                            cacheAllSaveGetIndexList.Remove(dr[fieldKey].ToString());
                            cacheAllSaveGetIndexList.Add(dr[fieldKey].ToString(), dr);
                        }
                    }
                }
                else
                {
                    row = 1;
                    addDataTableKey = DBName + ":" + TableName + ":" + row;
                    if (fieldKeyIndexList.ContainsKey(dr[fieldKey].ToString()) == false)
                    {
                        fieldKeyIndexList.Add(dr[fieldKey].ToString(), addDataTableKey);
                        cacheAllSaveGetIndexList.Add(dr[fieldKey].ToString(), dr);
                    }
                }
                cacheService.SetCache<DataRow>(addDataTableKey, dr, new TimeSpan(longShortTime, 0, CacheTimeLong, 0));
                cacheService.SetCache<string>(addDataTableFieldKey, addDataTableKey, new TimeSpan(longShortTime, 0, CacheTimeLong, 0));
                cacheService.SetCache<int>(DataTableRowsKey, row, new TimeSpan(longShortTime, 0, CacheTimeLong, 0));
                cacheService.SetCache<Dictionary<string, string>>(DataTableFieldKeyIndex, fieldKeyIndexList, new TimeSpan(longShortTime, 0, CacheTimeLong, 0));
                cacheService.SetCache<Dictionary<string, DataRow>>(DataTableCacheAllSaveGet, cacheAllSaveGetIndexList, new TimeSpan(longShortTime, 0, CacheTimeLong, 0));
                cacheService.SetCache<string>(DataTableKey, fieldKey, new TimeSpan(longShortTime, 0, CacheTimeLong, 0));
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return isAdd;
        }
         /// <summary>
         /// 增加表结构到缓存
         /// </summary>
         /// <param name="dt"></param>
         /// <param name="longType"></param>
         /// <returns></returns>
        public static bool AddDataTableStru(DataTable dt, int longType = 2)
        {
            bool isAdd = false;
            try
            {
                int longShortTime = 0;
                if (longType == 2)
                {
                    longShortTime = 350;
                }
                string structureName = DBName + ":" + dt.TableName + ":Structure";
                string strDataTableStru = TBaseJson.ToDataTableString(dt);
                cacheService.SetCache<string>(structureName, strDataTableStru, new TimeSpan(longShortTime, 0, CacheTimeLong, 0));
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return isAdd;
        }
        /// <summary>
        /// 通过表名获取表结构
        /// </summary>
        /// <param name="tableName"></param>
        /// <param name="longType"></param>
        /// <returns></returns>
        public static DataTable GetDataTableStru(string tableName, int longType = 2)
        {
            DataTable dataTable = new DataTable();
            try
            {
                string structureName = DBName + ":" + tableName + ":Structure";
                string structureStr = cacheService.GetCache<string>(structureName);
                dataTable = TBaseJson.ToDataTableByStru(structureStr);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return dataTable;
        }

        /// <summary>
        /// 暂时不使用,要使用时需要修正
        /// </summary>
        /// <param name="TableName"></param>
        /// <param name="dt"></param>
        /// <param name="keyField">多主键,使用豆号</param>
        /// <param name="longType"></param>
        /// <returns></returns>
        public static bool UpdateDataTableToCache(string TableName, DataTable dt, string fieldKey, int longType = 2)
        {
            bool isUpdate = false;
            try
            {
                foreach (DataRow dr in dt.Rows)
                {
                    string addDataTableFieldKKey = DBName + ":" + TableName + ":" + fieldKey + ":" + dr[fieldKey];
                    string addDataTableKey = cacheService.GetCache<string>(addDataTableFieldKKey);
                    DataRow tempDr = cacheService.GetCache<DataRow>(addDataTableKey);
                    DataTable tb = tempDr.Table;
                    List<string> ColumnNameList = new List<string>();
                    for (int i = 0; i < tb.Columns.Count; i++)
                    {
                        ColumnNameList.Add(tb.Columns[i].ColumnName);
                    }

                    foreach (string cn in ColumnNameList)
                    {
                        tempDr[cn] = dr[cn];
                    }
                }
                isUpdate = true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return isUpdate;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="TableName"></param>
        /// <param name="KeyFields">多主键,使用豆号</param>
        /// <param name="KeyFieldValues">多值,使用豆号</param>
        /// <returns></returns>
        public static bool DeleteDataRowToCache(string TableName, string KeyFields, string KeyFieldValues, int longType)
        {
            bool isDel = false;
            Dictionary<string, string> fieldKeyIndexList = new Dictionary<string, string>();
            Dictionary<string, DataRow> cacheAllSaveGetIndexList = new Dictionary<string, DataRow>();
            try
            {
                int longShortTime = 0;
                if (longType == 2)
                {
                    longShortTime = 350;
                }
                List<string> KeyFieldValuesList = KeyFieldValues.Split(',').ToList();
                string DataTableKey = DBName + ":" + TableName + ":" + "FieldKey";
                string fieldKey = cacheService.GetCache<string>(DataTableKey);
                string DataTableFieldKeyIndex = DBName + ":" + TableName + ":" + fieldKey + ":" + "Index";
                string DataTableCacheAllSaveGet = DBName + ":" + TableName + ":" + "CacheAllSaveGet";
                fieldKeyIndexList = cacheService.GetCache<Dictionary<string, string>>(DataTableFieldKeyIndex);
                cacheAllSaveGetIndexList = cacheService.GetCache<Dictionary<string, DataRow>>(DataTableCacheAllSaveGet);

                foreach (string tempValue in KeyFieldValuesList)
                {
                    cacheService.RemoveCacheByKey(fieldKeyIndexList[tempValue]);
                    if (fieldKeyIndexList.ContainsKey(tempValue) == true)
                    {                          
                        fieldKeyIndexList.Remove(tempValue);
                    }
                    if (cacheAllSaveGetIndexList.ContainsKey(tempValue) == true)
                    {
                        cacheAllSaveGetIndexList.Remove(tempValue);
                    } 
                }
                cacheService.SetCache<Dictionary<string, string>>(DataTableFieldKeyIndex, fieldKeyIndexList, new TimeSpan(longShortTime, 0, CacheTimeLong, 0));
                cacheService.SetCache<Dictionary<string, DataRow>>(DataTableCacheAllSaveGet, cacheAllSaveGetIndexList, new TimeSpan(longShortTime, 0, CacheTimeLong, 0));
                isDel = true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return isDel;
        }

        /// <summary>
        /// 暂时不使用,要使用时需要修正
        /// </summary>
        /// <param name="TableName"></param>
        /// <param name="whereStr">条件</param>
        /// <param name="longType">默认为2,一年有效</param>
        /// <returns></returns>
        public static bool DeleteDataRowToCache(string TableName, string whereStr, int longType)
        {
            bool isDel = false;
            try
            {
                int longShortTime = 0;
                if (longType == 2)
                {
                    longShortTime = 350;
                }
                DataTable dt = new DataTable();
                string DataTableRowsKey = DBName + ":" + TableName + ":" + MaxRows;
                int row = cacheService.GetCache<int>(DataTableRowsKey);
                int isClone = 0;
                for (int i = 1; i <= row; i++)
                {
                    string addDataTableKey = DBName + ":" + TableName + ":" + i;
                    DataRow dr = cacheService.GetCache<DataRow>(addDataTableKey);
                    if (dr != null)
                    {
                        isClone = isClone + 1;
                        if (isClone == 1)
                        {
                            dt = dr.Table.Clone();
                        }
                        DataTable tempDt = new DataTable();
                        tempDt = dr.Table.Clone();
                        tempDt.Rows.Add(dr.ItemArray);
                        DataRow[] tempDrs = tempDt.Select(whereStr);
                        foreach (var item in tempDrs)
                        {
                            cacheService.RemoveCacheByKey(addDataTableKey);
                            string DataTableDelRowsKey = DBName + ":" + TableName + ":" + MaxDelRows;
                            int k = cacheService.GetCache<int>(DataTableDelRowsKey);
                            if (k == 0)
                            {
                                k = 1;
                            }
                            else
                            {
                                k = k + 1;
                            }
                            cacheService.SetCache<int>(DataTableDelRowsKey, k, new TimeSpan(longShortTime, 0, CacheTimeLong, 0));
                        }
                    }
                }
                isDel = true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return isDel;
        }

        /// <summary>
        /// 通过缓存名,删除所有缓存
        /// </summary>
        /// <param name="TableName"></param>
        /// <param name="fieldKey">主键</param>
        /// <returns></returns>
        public static bool DeleteDataRowsByCache(string TableName, string fieldKey, int longType)
        {
            bool isDel = false;
            Dictionary<string, string> fieldKeyIndexList = new Dictionary<string, string>();
            Dictionary<string, DataRow> cacheAllSaveGetIndexList = new Dictionary<string, DataRow>();
            try
            {
                int longShortTime = 0;
                if (longType == 2)
                {
                    longShortTime = 350;
                }
                string DataTableKey = DBName + ":" + TableName + ":" + "FieldKey";
                //string fieldKey = cacheService.GetCache<string>(DataTableKey);
                string DataTableFieldKeyIndex = DBName + ":" + TableName + ":" + fieldKey + ":" + "Index";
                string DataTableCacheAllSaveGet = DBName + ":" + TableName + ":" + "CacheAllSaveGet";
                DataTable dt = new DataTable();
                string DataTableRowsKey = DBName + ":" + TableName + ":" + MaxRows;
                int row = cacheService.GetCache<int>(DataTableRowsKey);
                string DataTableDelRowsKey = DBName + ":" + TableName + ":" + MaxDelRows;
                int k = cacheService.GetCache<int>(DataTableDelRowsKey);
                int tempRows = k;
                for (int i = 1; i <= row - k; i++)
                {
                    int temp = k + i;
                    string addDataTableKey = DBName + ":" + TableName + ":" + temp;
                    cacheService.RemoveCacheByKey(addDataTableKey);
                    tempRows = tempRows + 1;
                    cacheService.SetCache<int>(DataTableDelRowsKey, tempRows, new TimeSpan(longShortTime, 0, CacheTimeLong, 0));                    
                }
                cacheService.RemoveCacheByKey(DataTableFieldKeyIndex);
                cacheService.RemoveCacheByKey(DataTableCacheAllSaveGet);
                isDel = true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return isDel;
        }

        public static DataTable GetFieldsByDt(DataTable dt, string[] fields)
        {
            //DataTable tempDt = dt.Copy();
            //List<string> fieldList = fields.ToList();
            删除列 
            //foreach (DataColumn col in dt.Columns)
            //{
            //    if (!fieldList.Contains(col.ColumnName))
            //    {
            //        tempDt.Columns.Remove(col.ColumnName);
            //    }
            //}

            DataTable tempDt = dt.DefaultView.ToTable(false, fields);
            return tempDt; 
        }

        /// <summary>
        /// 通过条件获取缓存
        /// </summary>
        /// <param name="TableName"></param>
        /// <param name="KeyFields"></param>
        /// <param name="KeyFieldValues"></param>
        /// <returns></returns>
        public static DataTable GetDataTableByCache(string TableName, string KeyFields, string KeyFieldValues)
        {
            DataTable dt = new DataTable();            
            try
            {
                string DataTableKey = DBName + ":" + TableName + ":" + "FieldKey";
                string fieldKey = cacheService.GetCache<string>(DataTableKey);
                if (fieldKey == null)
                {
                    dt = GetDataTableStru(TableName);
                    dt.TableName = TableName;
                    return dt;
                }

                int isClone = 0;
                if (fieldKey == KeyFields)
                {
                    foreach (string keyValue in KeyFieldValues.Split(','))
                    {
                        string addDataTableFieldKey = DBName + ":" + TableName + ":" + fieldKey + ":" + keyValue;
                        string addDataTableFieldKeyValue = cacheService.GetCache<string>(addDataTableFieldKey);
                        DataRow dr = cacheService.GetCache<DataRow>(addDataTableFieldKeyValue);
                        if (dr != null)
                        {
                            isClone = isClone + 1;
                            if (isClone == 1)
                            {
                                dt = dr.Table.Clone();
                            }
                            dt.Rows.Add(dr.ItemArray);
                        }
                    }
                }
                else
                {
                    string whereSql = "";
                    foreach (string keyValue in KeyFieldValues.Split(','))
                    {
                        if (string.IsNullOrEmpty(whereSql))
                        {
                            whereSql = KeyFields + "='" + keyValue + "'";
                        }
                        else
                        {
                            whereSql = " or " + KeyFields + "='" + keyValue + "'";
                        }
                    }
                    dt = GetDataTableByCache(TableName, whereSql);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            if (dt == null || dt.Rows.Count<1)
            {
                dt = GetDataTableStru(TableName);
            }
            dt.TableName = TableName;
            return dt;
        }

        /// <summary>
        /// 通过条件获取缓存
        /// </summary>
        /// <param name="TableName"></param>
        /// <param name="Fields"></param>
        /// <param name="KeyFields"></param>
        /// <param name="KeyFieldValues"></param>
        /// <returns></returns>
        public static DataTable GetDataTableByCache(string TableName, string[] Fields, string KeyFields, string KeyFieldValues)
        {
            DataTable dt = new DataTable();
            try
            {
                string DataTableKey = DBName + ":" + TableName + ":" + "FieldKey";
                string fieldKey = cacheService.GetCache<string>(DataTableKey);
                if (fieldKey == null)
                {
                    dt = GetDataTableStru(TableName);
                    dt.TableName = TableName;
                    return dt;
                }

                int isClone = 0;
                if (fieldKey == KeyFields)
                {
                    foreach (string keyValue in KeyFieldValues.Split(','))
                    {
                        string addDataTableFieldKey = DBName + ":" + TableName + ":" + fieldKey + ":" + keyValue;
                        string addDataTableFieldKeyValue = cacheService.GetCache<string>(addDataTableFieldKey);
                        DataRow dr = cacheService.GetCache<DataRow>(addDataTableFieldKeyValue);
                        if (dr != null)
                        {
                            isClone = isClone + 1;
                            if (isClone == 1)
                            {
                                dt = dr.Table.Clone();
                            }
                            dt.Rows.Add(dr.ItemArray);
                        }
                    }
                }
                else
                {
                    string whereSql = "";
                    foreach (string keyValue in KeyFieldValues.Split(','))
                    {
                        if (string.IsNullOrEmpty(whereSql))
                        {
                            whereSql = KeyFields + "='" + keyValue + "'";
                        }
                        else
                        {
                            whereSql = " or " + KeyFields + "='" + keyValue + "'";
                        }
                    }
                    dt = GetDataTableByCache(TableName, whereSql);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            if (dt == null || dt.Rows.Count < 1)
            {
                dt = GetDataTableStru(TableName);
            }
            dt.TableName = TableName;
            return GetFieldsByDt(dt, Fields);
        }

        /// <summary>
        /// 通过Key值获取缓存
        /// </summary>
        /// <param name="TableName"></param>
        /// <param name="KeyField"></param>
        /// <param name="KeyFieldValueList"></param>
        /// <returns></returns>
        public static DataTable GetDataTableByCache(string TableName, string KeyField, List<string> KeyFieldValueList)
        {
            DataTable dt = new DataTable();
            try
            {
                string DataTableKey = DBName + ":" + TableName + ":" + "FieldKey";
                string fieldKey = cacheService.GetCache<string>(DataTableKey);
                if (fieldKey == null)
                {
                    dt = GetDataTableStru(TableName);
                    dt.TableName = TableName;
                    return dt;
                }

                int isClone = 0;
                if (fieldKey == KeyField)
                {
                    foreach (string keyValue in KeyFieldValueList)
                    {
                        string addDataTableFieldKey = DBName + ":" + TableName + ":" + fieldKey + ":" + keyValue;
                        string addDataTableFieldKeyValue = cacheService.GetCache<string>(addDataTableFieldKey);
                        DataRow dr = cacheService.GetCache<DataRow>(addDataTableFieldKeyValue);
                        if (dr != null)
                        {
                            isClone = isClone + 1;
                            if (isClone == 1)
                            {
                                dt = dr.Table.Clone();
                            }
                            dt.Rows.Add(dr.ItemArray);
                        }
                    }
                }
                else
                {
                    string whereSql = "";
                    foreach (string keyValue in KeyFieldValueList)
                    {
                        if (string.IsNullOrEmpty(whereSql))
                        {
                            whereSql = KeyField + "='" + keyValue + "'";
                        }
                        else
                        {
                            whereSql = " or " + KeyField + "='" + keyValue + "'";
                        }
                    }
                    dt = GetDataTableByCache(TableName, whereSql);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            if (dt == null || dt.Rows.Count < 1)
            {
                dt = GetDataTableStru(TableName);
            }
            dt.TableName = TableName;
            return dt;
        }
        /// <summary>
        /// 通过Key值获取缓存
        /// </summary>
        /// <param name="TableName"></param>
        /// <param name="Fields"></param>
        /// <param name="KeyField"></param>
        /// <param name="KeyFieldValueList"></param>
        /// <returns></returns>
        public static DataTable GetDataTableByCache(string TableName, string[] Fields, string KeyField, List<string> KeyFieldValueList)
        {
            DataTable dt = new DataTable();
            try
            {
                string DataTableKey = DBName + ":" + TableName + ":" + "FieldKey";
                string fieldKey = cacheService.GetCache<string>(DataTableKey);
                if (fieldKey == null)
                {
                    dt = GetDataTableStru(TableName);
                    dt.TableName = TableName;
                    return dt;
                }

                int isClone = 0;
                if (fieldKey == KeyField)
                {
                    foreach (string keyValue in KeyFieldValueList)
                    {
                        string addDataTableFieldKey = DBName + ":" + TableName + ":" + fieldKey + ":" + keyValue;
                        string addDataTableFieldKeyValue = cacheService.GetCache<string>(addDataTableFieldKey);
                        DataRow dr = cacheService.GetCache<DataRow>(addDataTableFieldKeyValue);
                        if (dr != null)
                        {
                            isClone = isClone + 1;
                            if (isClone == 1)
                            {
                                dt = dr.Table.Clone();
                            }
                            dt.Rows.Add(dr.ItemArray);
                        }
                    }
                }
                else
                {
                    string whereSql = "";
                    foreach (string keyValue in KeyFieldValueList)
                    {
                        if (string.IsNullOrEmpty(whereSql))
                        {
                            whereSql = KeyField + "='" + keyValue + "'";
                        }
                        else
                        {
                            whereSql = " or " + KeyField + "='" + keyValue + "'";
                        }
                    }
                    dt = GetDataTableByCache(TableName, whereSql);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            if (dt == null || dt.Rows.Count < 1)
            {
                dt = GetDataTableStru(TableName);
            }
            dt.TableName = TableName;
            return GetFieldsByDt(dt, Fields);
        }

        /// <summary>
        /// 通过Key值列表获取缓存
        /// </summary>
        /// <param name="TableNameList"></param>
        /// <param name="KeyFieldList"></param>
        /// <param name="KeyFieldValuesList"></param>
        /// <returns></returns>
        public static DataSet GetDataSetByCache(List<string> TableNameList, List<string> KeyFieldList, List<List<string>> KeyFieldValuesList)
        {
            DataSet ds = new DataSet();
            try
            {
                int row = 0;
                foreach (string tableName in TableNameList)
                {
                    string KeyFields = KeyFieldList[row];
                    List<string> KeyFieldValues = KeyFieldValuesList[row];
                    ds.Tables.Add(GetDataTableByCache(tableName, KeyFields, KeyFieldValues));
                    row = row + 1;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return ds;
        }
        /// <summary>
        /// 通过Key值列表获取缓存
        /// </summary>
        /// <param name="TableNameList"></param>
        /// <param name="FieldsList"></param>
        /// <param name="KeyFieldList"></param>
        /// <param name="KeyFieldValuesList"></param>
        /// <returns></returns>
        public static DataSet GetDataSetByCache(List<string> TableNameList, List<string[]> FieldsList, List<string> KeyFieldList, List<List<string>> KeyFieldValuesList)
        {
            DataSet ds = new DataSet();
            try
            {
                int row = 0;
                foreach (string tableName in TableNameList)
                {
                    string KeyFields = KeyFieldList[row];
                    List<string> KeyFieldValues = KeyFieldValuesList[row];
                    ds.Tables.Add(GetDataTableByCache(tableName, FieldsList[row], KeyFields, KeyFieldValues.ToList()));
                    row = row + 1;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return ds;
        }

        /// <summary>
        /// 通过复杂条件获取缓存
        /// </summary>
        /// <param name="TableName">缓存表名</param>
        /// <param name="whereStr">条件</param>
        /// <returns>DataTable</returns>
        public static DataTable GetDataTableByCache(string TableName, string whereStr)
        {
            Dictionary<string, DataRow> cacheAllSaveGetIndexList = new Dictionary<string, DataRow>();
            DataTable dt = new DataTable();
            try
            {
                string DataTableRowsKey = DBName + ":" + TableName + ":" + MaxRows;
                int row = cacheService.GetCache<int>(DataTableRowsKey);
                int isClone = 0;
                string DataTableKey = DBName + ":" + TableName + ":" + "FieldKey";
                string fieldKey = cacheService.GetCache<string>(DataTableKey);
                string DataTableCacheAllSaveGet = DBName + ":" + TableName + ":" + "CacheAllSaveGet";
                cacheAllSaveGetIndexList = cacheService.GetCache<Dictionary<string, DataRow>>(DataTableCacheAllSaveGet);
                if (cacheAllSaveGetIndexList == null)
                {
                    dt = GetDataTableStru(TableName);
                    dt.TableName = TableName;
                    return dt;
                }

                DataTable tempDt = new DataTable();
                List<DataRow> drList = new List<DataRow>();
                foreach (KeyValuePair<string, DataRow> pair in cacheAllSaveGetIndexList)
                {
                    isClone = isClone + 1;
                    if (isClone == 1)
                    {
                        dt = pair.Value.Table.Clone();
                        tempDt = pair.Value.Table.Clone();
                    }
                    tempDt.Rows.Clear();
                    tempDt.Rows.Add(pair.Value.ItemArray);
                    DataRow[] tempDrs = tempDt.Select(whereStr);
                    if (tempDrs.Length > 0)
                    {
                        dt.Rows.Add(pair.Value.ItemArray);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            if (dt == null || dt.Rows.Count < 1)
            {
                dt = GetDataTableStru(TableName);
            }
            dt.TableName = TableName;
            return dt;
        }
        /// <summary>
        /// 通过复杂条件获取缓存
        /// </summary>
        /// <param name="TableName">缓存表名</param>
        /// <param name="Fields">字段名</param>
        /// <param name="whereStr">条件</param>
        /// <returns>DataTable</returns>
        public static DataTable GetDataTableByCache(string TableName, string[] Fields, string whereStr)
        {
            Dictionary<string, DataRow> cacheAllSaveGetIndexList = new Dictionary<string, DataRow>();
            DataTable dt = new DataTable();
            try
            {
                string DataTableRowsKey = DBName + ":" + TableName + ":" + MaxRows;
                int row = cacheService.GetCache<int>(DataTableRowsKey);
                int isClone = 0;
                string DataTableKey = DBName + ":" + TableName + ":" + "FieldKey";
                string fieldKey = cacheService.GetCache<string>(DataTableKey);
                string DataTableCacheAllSaveGet = DBName + ":" + TableName + ":" + "CacheAllSaveGet";
                cacheAllSaveGetIndexList = cacheService.GetCache<Dictionary<string, DataRow>>(DataTableCacheAllSaveGet);
                if (cacheAllSaveGetIndexList == null)
                {
                    dt = GetDataTableStru(TableName);
                    dt.TableName = TableName;
                    return dt;
                }

                DataTable tempDt = new DataTable();
                List<DataRow> drList = new List<DataRow>();
                foreach (KeyValuePair<string, DataRow> pair in cacheAllSaveGetIndexList)
                {
                    isClone = isClone + 1;
                    if (isClone == 1)
                    {
                        dt = pair.Value.Table.Clone();
                        tempDt = pair.Value.Table.Clone();
                    }
                    tempDt.Rows.Clear();
                    tempDt.Rows.Add(pair.Value.ItemArray);
                    DataRow[] tempDrs = tempDt.Select(whereStr);
                    if (tempDrs.Length > 0)
                    {
                        dt.Rows.Add(pair.Value.ItemArray);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            if (dt == null || dt.Rows.Count < 1)
            {
                dt = GetDataTableStru(TableName);
            }
            dt.TableName = TableName;
            return GetFieldsByDt(dt, Fields);
        }

        /// <summary>
        /// 通过条件列表获取多表缓存
        /// </summary>
        /// <param name="TableNameList">缓存表列表</param>
        /// <param name="whereStrList">条件列表</param>
        /// <returns>DataSet</returns>
        public static DataSet GetDataSetByCache(List<string> TableNameList, List<string> whereStrList)
        {
            DataSet ds = new DataSet();
            try
            {
                int row = 0;
                foreach (string tableName in TableNameList)
                {
                    string whereStr = whereStrList[row];
                    ds.Tables.Add(GetDataTableByCache(tableName, whereStr));
                    row = row + 1;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return ds;
        }
        /// <summary>
        /// 通过条件列表获取多表缓存
        /// </summary>
        /// <param name="TableNameList">缓存表列表</param>
        /// <param name="FieldsList">字段名列表</param>
        /// <param name="whereStrList">条件列表</param>
        /// <returns>DataSet</returns>
        public static DataSet GetDataSetByCache(List<string> TableNameList, List<string[]> FieldsList, List<string> whereStrList)
        {
            DataSet ds = new DataSet();
            try
            {
                int row = 0;
                foreach (string tableName in TableNameList)
                {
                    string whereStr = whereStrList[row];
                    ds.Tables.Add(GetDataTableByCache(tableName, FieldsList[row], whereStr));
                    row = row + 1;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return ds;
        }

        /// <summary>
        /// 通过条件获取多表的缓存
        /// </summary>
        /// <param name="TableNameList"></param>
        /// <param name="KeyFieldsList"></param>
        /// <param name="KeyFieldValuesList"></param>
        /// <returns></returns>
        public static DataSet GetDataSetByCache(List<string> TableNameList, List<string> KeyFieldsList, List<string> KeyFieldValuesList)
        {
            DataSet ds = new DataSet();
            try
            {
                int row = 0;
                foreach (string tableName in TableNameList)
                {
                    string KeyFields = KeyFieldsList[row];
                    string KeyFieldValues = KeyFieldValuesList[row];
                    ds.Tables.Add(GetDataTableByCache(tableName, KeyFields, KeyFieldValues));
                    row = row + 1;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return ds;
        }
        /// <summary>
        /// 通过条件获取多表的缓存
        /// </summary>
        /// <param name="TableNameList"></param>
        /// <param name="FieldsList">字段名列表</param>
        /// <param name="KeyFieldsList"></param>
        /// <param name="KeyFieldValuesList"></param>
        /// <returns></returns>
        public static DataSet GetDataSetByCache(List<string> TableNameList, List<string[]> FieldsList, List<string> KeyFieldsList, List<string> KeyFieldValuesList)
        {
            DataSet ds = new DataSet();
            try
            {
                int row = 0;
                foreach (string tableName in TableNameList)
                {
                    string KeyFields = KeyFieldsList[row];
                    string KeyFieldValues = KeyFieldValuesList[row];
                    ds.Tables.Add(GetDataTableByCache(tableName, FieldsList[row],KeyFields, KeyFieldValues));
                    row = row + 1;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return ds;
        }

        /// <summary>
        /// 通过名称获取缓存
        /// </summary>
        /// <param name="TableName"></param>
        /// <returns></returns>
        public static DataTable GetDataTableByCache(string TableName)
        {
            Dictionary<string, DataRow> cacheAllSaveGetIndexList = new Dictionary<string, DataRow>();
            DataTable dt = new DataTable();
            try
            {
                string DataTableRowsKey = DBName + ":" + TableName + ":" + MaxRows;
                int row = cacheService.GetCache<int>(DataTableRowsKey);
                int isClone = 0;
                string DataTableKey = DBName + ":" + TableName + ":" + "FieldKey";
                string fieldKey = cacheService.GetCache<string>(DataTableKey);
                string DataTableCacheAllSaveGet = DBName + ":" + TableName + ":" + "CacheAllSaveGet";
                cacheAllSaveGetIndexList = cacheService.GetCache<Dictionary<string, DataRow>>(DataTableCacheAllSaveGet);
                if (cacheAllSaveGetIndexList == null)
                {
                    dt = GetDataTableStru(TableName);
                    dt.TableName = TableName;
                    return dt;
                }

                foreach (KeyValuePair<string, DataRow> pair in cacheAllSaveGetIndexList)
                {
                    isClone = isClone + 1;
                    if (isClone == 1)
                    {
                        dt = pair.Value.Table.Clone();
                    }
                    dt.Rows.Add(pair.Value.ItemArray);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            if (dt == null || dt.Rows.Count < 1)
            {
                dt = GetDataTableStru(TableName);
            }
            dt.TableName = TableName;
            return dt;
        }

        /// <summary>
        /// 通过名称获取缓存
        /// </summary>
        /// <param name="TableName"></param>
        /// <param name="Fields"></param>
        /// <returns></returns>
        public static DataTable GetDataTableByCache(string TableName, string[] Fields)
        {
            Dictionary<string, DataRow> cacheAllSaveGetIndexList = new Dictionary<string, DataRow>();
            DataTable dt = new DataTable();
            try
            {
                string DataTableRowsKey = DBName + ":" + TableName + ":" + MaxRows;
                int row = cacheService.GetCache<int>(DataTableRowsKey);
                int isClone = 0;
                string DataTableKey = DBName + ":" + TableName + ":" + "FieldKey";
                string fieldKey = cacheService.GetCache<string>(DataTableKey);
                string DataTableCacheAllSaveGet = DBName + ":" + TableName + ":" + "CacheAllSaveGet";
                cacheAllSaveGetIndexList = cacheService.GetCache<Dictionary<string, DataRow>>(DataTableCacheAllSaveGet);
                if (cacheAllSaveGetIndexList == null)
                {
                    dt = GetDataTableStru(TableName);
                    dt.TableName = TableName;
                    return dt;
                }

                foreach (KeyValuePair<string, DataRow> pair in cacheAllSaveGetIndexList)
                {
                    isClone = isClone + 1;
                    if (isClone == 1)
                    {
                        dt = pair.Value.Table.Clone();
                    }
                    dt.Rows.Add(pair.Value.ItemArray);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            if (dt == null || dt.Rows.Count < 1)
            {
                dt = GetDataTableStru(TableName);
            }
            dt.TableName = TableName;
            return GetFieldsByDt(dt,Fields);
        }

        /// <summary>
        /// 通过名称及条件获取缓存分页
        /// </summary>
        /// <param name="TableName">缓存表名</param>
        /// <param name="whereStr">条件:无条件时传"1=1"</param>
        /// <param name="pageNo">页码,注意:从1开始</param>
        /// <param name="pageSize">每页条数</param>
        /// <param name="totalPage">总页数</param>
        /// <param name="fieldOrderBy">列名,ASC/DESC 升序/降序排列,如:Age ASC或Age DESC</param>
        /// <returns>指定页码的DataTable数据</returns>
        public static DataTable GetDataTableByCache(string TableName, string whereStr, int pageNo, int pageSize, ref int totalPage, string fieldOrderBy = "")
        {
            int totalRows = 0;
            DataTable onePageTable = new DataTable();
            try
            {
                whereStr = whereStr.ToUpper();
                string DataTableRowsKey = DBName + ":" + TableName + ":" + MaxRows;
                int row = cacheService.GetCache<int>(DataTableRowsKey);
                int isClone = 0;
                var rowBegin = (pageNo - 1) * pageSize;
                var rowEnd = pageNo * pageSize;

                Dictionary<string, string> fieldKeyIndexList = new Dictionary<string, string>();

                string DataTableKey = DBName + ":" + TableName + ":" + "FieldKey";
                string tempDataTableKeyValue = cacheService.GetCache<string>(DataTableKey);
                string DataTableKeyValue = DBName + ":" + TableName + ":" + tempDataTableKeyValue;
                string DataTableFieldKeyIndex = DataTableKeyValue + ":" + "Index";

                if (whereStr.Replace(" ", "") == "1=1")
                {
                    totalRows = GetDataTableCountByCache(TableName);
                    totalPage = getTotalPage(totalRows, pageSize);
                    fieldKeyIndexList = cacheService.GetCache<Dictionary<string, string>>(DataTableFieldKeyIndex);
                    if (fieldKeyIndexList == null)
                    {
                        onePageTable = GetDataTableStru(TableName);
                        onePageTable.TableName = TableName;
                        return onePageTable;
                    }
                    int tempRows = 0;
                    foreach (KeyValuePair<string, string> pair in fieldKeyIndexList)
                    {
                        if (tempRows >= rowBegin & tempRows <= rowEnd)
                        {
                            DataRow dr = cacheService.GetCache<DataRow>(pair.Value);
                            if (tempRows == rowBegin)
                            {
                                onePageTable = dr.Table.Clone();
                            }
                            onePageTable.Rows.Add(dr.ItemArray);
                            if (tempRows == (rowEnd - 1))
                            {
                                return onePageTable;
                            }
                        }
                        tempRows = tempRows + 1;
                    }
                }
                else
                {
                    string fieldKey = cacheService.GetCache<string>(DataTableKey);
                    string DataTableCacheAllSaveGet = DBName + ":" + TableName + ":" + "CacheAllSaveGet";
                    Dictionary<string, DataRow> cacheAllSaveGetIndexList = new Dictionary<string, DataRow>();
                    cacheAllSaveGetIndexList = cacheService.GetCache<Dictionary<string, DataRow>>(DataTableCacheAllSaveGet);
                    if (cacheAllSaveGetIndexList == null)
                    {
                        onePageTable = GetDataTableStru(TableName);
                        onePageTable.TableName = TableName;
                        return onePageTable;
                    }

                    DataTable tempDt = new DataTable();
                    List<DataRow> drList = new List<DataRow>();
                    foreach (KeyValuePair<string, DataRow> pair in cacheAllSaveGetIndexList)
                    {
                        isClone = isClone + 1;
                        if (isClone == 1)
                        {
                            onePageTable = pair.Value.Table.Clone();
                            tempDt = pair.Value.Table.Clone();
                        }
                        tempDt.Rows.Clear();
                        tempDt.Rows.Add(pair.Value.ItemArray);
                        DataRow[] tempDrs = tempDt.Select(whereStr);
                        if (tempDrs.Length > 0)
                        {
                            if (totalRows >= rowBegin & totalRows < rowEnd)
                            {
                                onePageTable.Rows.Add(pair.Value.ItemArray);
                            }
                            totalRows = totalRows + 1;
                        }
                    }
                }
                totalPage = getTotalPage(totalRows, pageSize);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            if (onePageTable == null || onePageTable.Rows.Count < 1)
            {
                onePageTable = GetDataTableStru(TableName);
            }
            onePageTable.TableName = TableName;
            return onePageTable;
        }
        /// <summary>
        /// 通过名称及条件获取缓存分页
        /// </summary>
        /// <param name="TableName">缓存表名</param>
        /// <param name="Fields">返回的字段名</param>
        /// <param name="whereStr">条件:无条件时传"1=1"</param>
        /// <param name="pageNo">页码,注意:从1开始</param>
        /// <param name="pageSize">每页条数</param>
        /// <param name="totalPage">总页数</param>
        /// <param name="fieldOrderBy">列名,ASC/DESC 升序/降序排列,如:Age ASC或Age DESC</param>
        /// <returns>指定页码的DataTable数据</returns>
        public static DataTable GetDataTableByCache(string TableName, string[] Fields, string whereStr, int pageNo, int pageSize, ref int totalPage, string fieldOrderBy = "")
        {
            int totalRows = 0;
            DataTable onePageTable = new DataTable();
            try
            {
                whereStr = whereStr.ToUpper();
                string DataTableRowsKey = DBName + ":" + TableName + ":" + MaxRows;
                int row = cacheService.GetCache<int>(DataTableRowsKey);
                int isClone = 0;
                var rowBegin = (pageNo - 1) * pageSize;
                var rowEnd = pageNo * pageSize;

                Dictionary<string, string> fieldKeyIndexList = new Dictionary<string, string>();

                string DataTableKey = DBName + ":" + TableName + ":" + "FieldKey";
                string tempDataTableKeyValue = cacheService.GetCache<string>(DataTableKey);
                string DataTableKeyValue = DBName + ":" + TableName + ":" + tempDataTableKeyValue;
                string DataTableFieldKeyIndex = DataTableKeyValue + ":" + "Index";

                if (whereStr.Replace(" ", "") == "1=1")
                {
                    totalRows = GetDataTableCountByCache(TableName);
                    totalPage = getTotalPage(totalRows, pageSize);
                    fieldKeyIndexList = cacheService.GetCache<Dictionary<string, string>>(DataTableFieldKeyIndex);
                    if (fieldKeyIndexList == null)
                    {
                        onePageTable = GetDataTableStru(TableName);
                        onePageTable.TableName = TableName;
                        return onePageTable;
                    }
                    int tempRows = 0;
                    foreach (KeyValuePair<string, string> pair in fieldKeyIndexList)
                    {
                        if (tempRows >= rowBegin & tempRows <= rowEnd)
                        {
                            DataRow dr = cacheService.GetCache<DataRow>(pair.Value);
                            if (tempRows == rowBegin)
                            {
                                onePageTable = dr.Table.Clone();
                            }
                            onePageTable.Rows.Add(dr.ItemArray);
                            if (tempRows == (rowEnd - 1))
                            {
                                return onePageTable;
                            }
                        }
                        tempRows = tempRows + 1;
                    }
                }
                else
                {
                    string fieldKey = cacheService.GetCache<string>(DataTableKey);
                    string DataTableCacheAllSaveGet = DBName + ":" + TableName + ":" + "CacheAllSaveGet";
                    Dictionary<string, DataRow> cacheAllSaveGetIndexList = new Dictionary<string, DataRow>();
                    cacheAllSaveGetIndexList = cacheService.GetCache<Dictionary<string, DataRow>>(DataTableCacheAllSaveGet);
                    if (cacheAllSaveGetIndexList == null)
                    {
                        onePageTable = GetDataTableStru(TableName);
                        onePageTable.TableName = TableName;
                        return GetFieldsByDt(onePageTable, Fields);
                    }

                    DataTable tempDt = new DataTable();
                    List<DataRow> drList = new List<DataRow>();
                    foreach (KeyValuePair<string, DataRow> pair in cacheAllSaveGetIndexList)
                    {
                        isClone = isClone + 1;
                        if (isClone == 1)
                        {
                            onePageTable = pair.Value.Table.Clone();
                            tempDt = pair.Value.Table.Clone();
                        }
                        tempDt.Rows.Clear();
                        tempDt.Rows.Add(pair.Value.ItemArray);
                        DataRow[] tempDrs = tempDt.Select(whereStr);
                        if (tempDrs.Length > 0)
                        {
                            if (totalRows >= rowBegin & totalRows < rowEnd)
                            {
                                onePageTable.Rows.Add(pair.Value.ItemArray);
                            }
                            totalRows = totalRows + 1;
                        }
                    }
                }
                totalPage = getTotalPage(totalRows, pageSize);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            if (onePageTable == null || onePageTable.Rows.Count < 1)
            {
                onePageTable = GetDataTableStru(TableName);
            }
            onePageTable.TableName = TableName;
            return GetFieldsByDt(onePageTable, Fields);
        }

        /// <summary>
        /// 通过名称及条件获取缓存分页
        /// </summary>
        /// <param name="TableName">缓存表名</param>
        /// <param name="whereStr">条件:无条件时传"1=1"</param>
        /// <param name="pageNo">页码,注意:从1开始</param>
        /// <param name="pageSize">每页条数</param>
        /// <param name="totalPage">总页数</param>
        /// <param name="totalRows">总行数</param>
        /// <param name="fieldOrderBy">列名,ASC/DESC 升序/降序排列,如:Age ASC或Age DESC</param>
        /// <returns>指定页码的DataTable数据</returns>
        public static DataTable GetDataTableByCache(string TableName, string whereStr, int pageNo, int pageSize, ref int totalPage,ref int totalRows, string fieldOrderBy = "")
        {
            DataTable onePageTable = new DataTable();
            try
            {
                whereStr = whereStr.ToUpper();
                string DataTableRowsKey = DBName + ":" + TableName + ":" + MaxRows;
                int row = cacheService.GetCache<int>(DataTableRowsKey);
                int isClone = 0;
                var rowBegin = (pageNo - 1) * pageSize;
                var rowEnd = pageNo * pageSize;

                Dictionary<string, string> fieldKeyIndexList = new Dictionary<string, string>();
                
                string DataTableKey = DBName + ":" + TableName + ":" + "FieldKey";
                string tempDataTableKeyValue = cacheService.GetCache<string>(DataTableKey);
                string DataTableKeyValue = DBName + ":" + TableName + ":" + tempDataTableKeyValue;
                string DataTableFieldKeyIndex = DataTableKeyValue + ":" + "Index";

                if (whereStr.Replace(" ", "") == "1=1")
                {
                    totalRows = GetDataTableCountByCache(TableName);
                    totalPage = getTotalPage(totalRows, pageSize);
                    fieldKeyIndexList = cacheService.GetCache<Dictionary<string, string>>(DataTableFieldKeyIndex);
                    if (fieldKeyIndexList == null)
                    {
                        onePageTable = GetDataTableStru(TableName);
                        onePageTable.TableName = TableName;
                        return onePageTable;
                    }
                    int tempRows = 0;
                    foreach (KeyValuePair<string, string> pair in fieldKeyIndexList)
                    {
                        if (tempRows >= rowBegin & tempRows <= rowEnd)
                        {
                            DataRow dr = cacheService.GetCache<DataRow>(pair.Value);
                            if (tempRows == rowBegin)
                            {
                                onePageTable = dr.Table.Clone();
                            }
                            onePageTable.Rows.Add(dr.ItemArray);
                            if (tempRows == (rowEnd -1))
                            {
                                return onePageTable;
                            }
                        }
                        tempRows = tempRows + 1;
                    }
                }
                else
                {
                    string fieldKey = cacheService.GetCache<string>(DataTableKey);
                    string DataTableCacheAllSaveGet = DBName + ":" + TableName + ":" + "CacheAllSaveGet";
                    Dictionary<string, DataRow> cacheAllSaveGetIndexList = new Dictionary<string, DataRow>();
                    cacheAllSaveGetIndexList = cacheService.GetCache<Dictionary<string, DataRow>>(DataTableCacheAllSaveGet);
                    if (cacheAllSaveGetIndexList == null)
                    {
                        onePageTable = GetDataTableStru(TableName);
                        onePageTable.TableName = TableName;
                        return onePageTable;
                    }

                    DataTable tempDt = new DataTable();
                    List<DataRow> drList = new List<DataRow>();
                    foreach (KeyValuePair<string, DataRow> pair in cacheAllSaveGetIndexList)
                    {
                        isClone = isClone + 1;
                        if (isClone == 1)
                        {
                            onePageTable = pair.Value.Table.Clone();
                            tempDt = pair.Value.Table.Clone();
                        }
                        tempDt.Rows.Clear();
                        tempDt.Rows.Add(pair.Value.ItemArray);
                        DataRow[] tempDrs = tempDt.Select(whereStr);
                        if (tempDrs.Length > 0)
                        {
                            if (totalRows >= rowBegin & totalRows < rowEnd)
                            {
                                onePageTable.Rows.Add(pair.Value.ItemArray);
                            }
                            totalRows = totalRows + 1;
                        }
                    }
                }
                totalPage = getTotalPage(totalRows, pageSize);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            if (onePageTable == null || onePageTable.Rows.Count < 1)
            {
                onePageTable = GetDataTableStru(TableName);
            }
            onePageTable.TableName = TableName;
            return onePageTable;
        }
        /// <summary>
        /// 通过名称及条件获取缓存分页
        /// </summary>
        /// <param name="TableName">缓存表名</param>
        /// <param name="Fields">返回的字段名</param>
        /// <param name="whereStr">条件:无条件时传"1=1"</param>
        /// <param name="pageNo">页码,注意:从1开始</param>
        /// <param name="pageSize">每页条数</param>
        /// <param name="totalPage">总页数</param>
        /// <param name="totalRows">总行数</param>
        /// <param name="fieldOrderBy">列名,ASC/DESC 升序/降序排列,如:Age ASC或Age DESC</param>
        /// <returns>指定页码的DataTable数据</returns>
        public static DataTable GetDataTableByCache(string TableName, string[] Fields, string whereStr, int pageNo, int pageSize, ref int totalPage, ref int totalRows, string fieldOrderBy = "")
        {
            DataTable onePageTable = new DataTable();
            try
            {
                whereStr = whereStr.ToUpper();
                string DataTableRowsKey = DBName + ":" + TableName + ":" + MaxRows;
                int row = cacheService.GetCache<int>(DataTableRowsKey);
                int isClone = 0;
                var rowBegin = (pageNo - 1) * pageSize;
                var rowEnd = pageNo * pageSize;

                Dictionary<string, string> fieldKeyIndexList = new Dictionary<string, string>();

                string DataTableKey = DBName + ":" + TableName + ":" + "FieldKey";
                string tempDataTableKeyValue = cacheService.GetCache<string>(DataTableKey);
                string DataTableKeyValue = DBName + ":" + TableName + ":" + tempDataTableKeyValue;
                string DataTableFieldKeyIndex = DataTableKeyValue + ":" + "Index";

                if (whereStr.Replace(" ", "") == "1=1")
                {
                    totalRows = GetDataTableCountByCache(TableName);
                    totalPage = getTotalPage(totalRows, pageSize);
                    fieldKeyIndexList = cacheService.GetCache<Dictionary<string, string>>(DataTableFieldKeyIndex);
                    if (fieldKeyIndexList == null)
                    {
                        onePageTable = GetDataTableStru(TableName);
                        onePageTable.TableName = TableName;
                        return onePageTable;
                    }
                    int tempRows = 0;
                    foreach (KeyValuePair<string, string> pair in fieldKeyIndexList)
                    {
                        if (tempRows >= rowBegin & tempRows <= rowEnd)
                        {
                            DataRow dr = cacheService.GetCache<DataRow>(pair.Value);
                            if (tempRows == rowBegin)
                            {
                                onePageTable = dr.Table.Clone();
                            }
                            onePageTable.Rows.Add(dr.ItemArray);
                            if (tempRows == (rowEnd - 1))
                            {
                                return GetFieldsByDt(onePageTable, Fields);
                            }
                        }
                        tempRows = tempRows + 1;
                    }
                }
                else
                {
                    string fieldKey = cacheService.GetCache<string>(DataTableKey);
                    string DataTableCacheAllSaveGet = DBName + ":" + TableName + ":" + "CacheAllSaveGet";
                    Dictionary<string, DataRow> cacheAllSaveGetIndexList = new Dictionary<string, DataRow>();
                    cacheAllSaveGetIndexList = cacheService.GetCache<Dictionary<string, DataRow>>(DataTableCacheAllSaveGet);
                    if (cacheAllSaveGetIndexList == null)
                    {
                        onePageTable = GetDataTableStru(TableName);
                        onePageTable.TableName = TableName;
                        return onePageTable;
                    }

                    DataTable tempDt = new DataTable();
                    List<DataRow> drList = new List<DataRow>();
                    foreach (KeyValuePair<string, DataRow> pair in cacheAllSaveGetIndexList)
                    {
                        isClone = isClone + 1;
                        if (isClone == 1)
                        {
                            onePageTable = pair.Value.Table.Clone();
                            tempDt = pair.Value.Table.Clone();
                        }
                        tempDt.Rows.Clear();
                        tempDt.Rows.Add(pair.Value.ItemArray);
                        DataRow[] tempDrs = tempDt.Select(whereStr);
                        if (tempDrs.Length > 0)
                        {
                            if (totalRows >= rowBegin & totalRows < rowEnd)
                            {
                                onePageTable.Rows.Add(pair.Value.ItemArray);
                            }
                            totalRows = totalRows + 1;
                        }
                    }
                }
                totalPage = getTotalPage(totalRows, pageSize);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            if (onePageTable == null || (onePageTable.Rows.Count + onePageTable.Columns.Count) < 1)
            {
                onePageTable = GetDataTableStru(TableName);
            }
            onePageTable.TableName = TableName;
            return GetFieldsByDt(onePageTable, Fields);
        }

        /// <summary>
        /// 返回分页后的总页数
        /// </summary>
        /// <param name="totalCount">总记录条数</param>
        /// <param name="pageSize">每页显示条数</param>
        /// <returns>总页数</returns>
        public static int getTotalPage(int totalCount, int pageSize)
        {
            var totalPage = (totalCount / pageSize) + (totalCount % pageSize > 0 ? 1 : 0);
            return totalPage;
        }

        /// <summary>
        /// 初始化加载缓存
        /// </summary>
        /// <param name="TableName"></param>
        /// <param name="dt"></param>
        /// <param name="fieldKey"></param>
        /// <param name="longType"></param>
        /// <returns></returns>
        public static bool LoadDataTableToCache(string TableName, DataTable dt, string fieldKey, int longType)
        {
            bool isAdd = false;
            try
            {
                int longShortTime = 0;
                if (longType == 2)
                {
                    longShortTime = 350;
                }
                foreach (DataRow dr in dt.Rows)
                {
                    AddDataTableToCache(TableName, dr, fieldKey, longType);
                }
                string DataTableRowsKey = DBName + ":" + TableName + ":" + KeyField;
                cacheService.SetCache<string>(DataTableRowsKey, fieldKey, new TimeSpan(longShortTime, 0, CacheTimeLong, 0));
                isAdd = true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return isAdd;
        }

        /// <summary>
        /// 重新加载缓存
        /// </summary>
        /// <param name="TableName"></param>
        /// <param name="dt"></param>
        /// <param name="fieldKey"></param>
        /// <param name="longType"></param>
        /// <returns></returns>
        public static bool ReLoadDataTableToCache(string TableName, DataTable dt, string fieldKey, int longType)
        {
            bool isAdd = false;
            try
            {
                DeleteDataRowsByCache(TableName, fieldKey, longType);
                int longShortTime = 0;
                if (longType == 2)
                {
                    longShortTime = 350;
                }
                foreach (DataRow dr in dt.Rows)
                {
                    AddDataTableToCache(TableName, dr, fieldKey, longType);
                }
                string DataTableRowsKey = DBName + ":" + TableName + ":" + KeyField;
                cacheService.SetCache<string>(DataTableRowsKey, fieldKey, new TimeSpan(longShortTime, 0, CacheTimeLong, 0));
                isAdd = true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return isAdd;
        }

        /// <summary>
        /// 记录增加到缓存
        /// </summary>
        /// <param name="TableName"></param>
        /// <param name="dt"></param>
        /// <param name="fieldKey"></param>
        /// <param name="longType"></param>
        /// <returns></returns>
        public static bool AddDataTableToCache(string TableName, DataTable dt, string fieldKey, int longType)
        {
            bool isAdd = false;
            try
            {
                int longShortTime = 0;
                if (longType == 2)
                {
                    longShortTime = 350;
                }
                foreach (DataRow dr in dt.Rows)
                {
                    AddDataTableToCache(TableName, dr, fieldKey, longType);
                }
                string DataTableRowsKey = DBName + ":" + TableName + ":" + KeyField;
                cacheService.SetCache<string>(DataTableRowsKey, fieldKey, new TimeSpan(longShortTime, 0, CacheTimeLong, 0));
                isAdd = true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return isAdd;
        }
        /// <summary>
        /// 获取表名下的缓存个数
        /// </summary>
        /// <param name="TableName"></param>
        /// <returns></returns>
        public static int GetDataTableCountByCache(string TableName)
        {
            int DataTableRows;
            int DataTableDelRows;
            try
            {
                string DataTableRowsKey = DBName + ":" + TableName + ":" + MaxRows;
                DataTableRows = cacheService.GetCache<int>(DataTableRowsKey);
                string DataTableDelRowsKey = DBName + ":" + TableName + ":" + MaxDelRows;
                DataTableDelRows = cacheService.GetCache<int>(DataTableDelRowsKey);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return DataTableRows - DataTableDelRows;
        }
        /// <summary>
        /// 加载对象到缓存
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="cacheName"></param>
        /// <param name="t"></param>
        /// <param name="longType"></param>
        /// <returns></returns>
        public static bool LoadObjectToCache<T>(string cacheName, T t, int longType)
        {
            bool isLoad = false;
            try
            {
                int longShortTime = 0;
                if (longType == 2)
                {
                    longShortTime = 350;
                }
                cacheService.SetCache<T>(cacheName, t, new TimeSpan(longShortTime, 0, CacheTimeLong, 0));
                isLoad = true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return isLoad;
        }
    }
}
 

四、内存数据库驱动

内存数据库的驱动,分两块,第一种为以普通缓存来做,第二种以Redis集群来做

驱动适配器(CacheType = 2为普通缓存方式,CacheType = 1为Redis集群方式)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using ServiceStack.Redis;
using Newtonsoft.Json;

namespace QPCenterExpress.CoreSafe.CacheBase
{
    public class CacheService
    {
        static int CacheType = 2;

        public CacheService()
        {
            //var cacheTypeTypeTemp = ConfigurationManager.AppSettings["CacheType"];
            //if (cacheTypeTypeTemp != null)
            //{
            //    CacheType = Convert.ToInt32(cacheTypeTypeTemp);
            //}
        }
        /// <summary>  
        /// 获取数据缓存  
        /// </summary>  
        /// <param name="cacheKey">键</param>  
        public T GetCache<T>(string cacheKey)
        {
            T item = default(T);
            try
            {
                var temp = new object();
                if (CacheType == 2)
                {
                    temp = CacheHelper.GetCache(cacheKey);
                    item = (T)temp;
                }
                if (CacheType == 1)
                {
                    //temp = Redis.RedisBase.Item_Get<SysModel.TSysParm>(cacheKey);
                    string s = RedisBase.Item_Get<string>(cacheKey);
                    if (!string.IsNullOrEmpty(s))
                    {
                        item = Newtonsoft.Json.JsonConvert.DeserializeObject<T>(s);
                    }
                    //item = Newtonsoft.Json.JsonConvert.DeserializeObject<T>((string)temp);
                }
            }
            catch(Exception e)
            {
                //Log.LogMsgHelper.WriteLogsToQueue(Model.Enum.LogLevel.ERROR, Model.Enum.SysType.Core, Model.Enum.LogType.SysLog, cacheKey, "取缓存出错", e.ToString(), DateTime.Now, DateTime.Now, "GetCache");
            }

            return item;
        }

        /// <summary>  
        /// 设置缓存  
        /// </summary> 
        /// <typeparam name="T"></typeparam>   
        /// <param name="key"></param>      
        /// <param name="t"></param>             
        /// <param name="timeSpan"></param>     
        /// <returns></returns>   
        public void SetCache<T>(string cacheKey, T t, TimeSpan expiresIn)
        {
            try
            {
                if (CacheType == 2)
                {
                    TimeSpan ts = new TimeSpan(360, 0, 0, 0);
                    if (expiresIn > ts)
                    {
                        CacheHelper.SetCache(cacheKey, t, ts);
                    }
                    else
                    {
                        CacheHelper.SetCache(cacheKey, t, expiresIn);
                    }
                }
                if (CacheType == 1)
                {
                    string s = Newtonsoft.Json.JsonConvert.SerializeObject(t);
                    RedisBase.Item_Set<string>(cacheKey, s, expiresIn);
                }
            }
            catch (Exception e)
            {
                //Log.LogMsgHelper.WriteLogsToQueue(Model.Enum.LogLevel.ERROR, Model.Enum.SysType.Core, Model.Enum.LogType.SysLog, t, "存缓存出错", e.ToString(), DateTime.Now, DateTime.Now, "SetCache");
            }
        }

        /// <summary>  
        /// 设置缓存  
        /// </summary> 
        /// <typeparam name="T"></typeparam>   
        /// <param name="key"></param>      
        /// <param name="t"></param>           
        /// <returns></returns>   
        public void SetCache<T>(string cacheKey, T t)
        {
            try
            {
                if (CacheType == 2)
                {
                    CacheHelper.SetCache(cacheKey, t);
                }
                if (CacheType == 1)
                {
                    RedisBase.Item_Set<T>(cacheKey, t);
                }
            }
            catch (Exception e)
            {
                //Log.LogMsgHelper.WriteLogsToQueue(Model.Enum.LogLevel.ERROR, Model.Enum.SysType.Core, Model.Enum.LogType.SysLog, t, "存缓存出错", e.ToString(), DateTime.Now, DateTime.Now, "SetCache");
            }
        }

        /// <summary>  
        /// 移除缓存 
        /// </summary> 
        /// <param name="key"></param> 
        public bool RemoveCacheByKey(string cacheKey)
        {
            bool isRemove = false;
            try
            {
                if (CacheType == 2)
                {
                    CacheHelper.RemoveCacheByKey(cacheKey);
                    isRemove = true;
                }
                if (CacheType == 1)
                {
                    RedisBase.Item_Remove(cacheKey);
                    isRemove = true;
                }
            }
            catch (Exception e)
            {
                //Log.LogMsgHelper.WriteLogsToQueue(Model.Enum.LogLevel.ERROR, Model.Enum.SysType.Core, Model.Enum.LogType.SysLog, cacheKey, "移除缓存出错", e.ToString(), DateTime.Now, DateTime.Now, "RemoveCacheByKey");
            }
            return isRemove;
        }
    }
}
 

1、Redis集群驱动方式

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using ServiceStack.Redis;
using ServiceStack.Text;
using ServiceStack.Redis.Generic;
using ServiceStack.Common;
using System.Configuration;

namespace QPCenterExpress.CoreSafe.CacheBase
{
    public class RedisBase
    {
        //private static string WriteServerList = System.Configuration.ConfigurationSettings.AppSettings["WriteServerList"];
        //private static string ReadServerList = System.Configuration.ConfigurationSettings.AppSettings["ReadServerList"];
        //private static string MaxWritePoolSize = System.Configuration.ConfigurationSettings.AppSettings["MaxWritePoolSize"];
        //private static string MaxReadPoolSize = System.Configuration.ConfigurationSettings.AppSettings["MaxReadPoolSize"];
        //private static string AutoStart = System.Configuration.ConfigurationSettings.AppSettings["AutoStart"];

        #region -- 连接信息 --

        //10.0.18.8:6379 

        public static PooledRedisClientManager prcm = CreateManager();

        private static string[] SplitString(string strSource, string split)
        {
            return strSource.Split(split.ToArray());
        }

        private static PooledRedisClientManager CreateManager()
        {
            //RedisSettingsManager redisset = new RedisSettingsManager();
            //RedisSettings rediss = redisset.LoadSettings();

            //string[] writeServerList = SplitString(rediss.WriteServerList, ",");
            //string[] readServerList = SplitString(rediss.ReadServerList, ",");

            string[] writeServerList = SplitString(ConfigurationManager.AppSettings["writeServerList"].ToString(), ",");
            string[] readServerList = SplitString(ConfigurationManager.AppSettings["readServerList"].ToString(), ",");

            // 支持读写分离,均衡负载  

            return new PooledRedisClientManager(writeServerList, readServerList, new RedisClientManagerConfig  
            {    
                MaxWritePoolSize = writeServerList.Length * ConfigurationManager.AppSettings["MaxWritePoolSize"].ToInt(), // “写”链接池链接数  
                MaxReadPoolSize = readServerList.Length * ConfigurationManager.AppSettings["MaxReadPoolSize"].ToInt(), // “读”链接池链接数     
                //AutoStart = rediss.AutoStart,   
                //MaxWritePoolSize = writeServerList.Length * 5, // “写”链接池链接数   
                //MaxReadPoolSize = readServerList.Length * 5, // “读”链接池链接数   
                AutoStart = true,  
            });

        }

        #endregion

        #region -- Item --

        /// <summary>  
        /// 设置单体 
        /// </summary>  
        /// <typeparam name="T"></typeparam> 
        /// <param name="key"></param>  
        /// <param name="t"></param>  
        /// <param name="timeSpan"></param> 
        /// <returns></returns> 
        public static bool Item_Set<T>(string key, T t)
        {
            IRedisClient redis = prcm.GetClient();
            var item = redis.Set<T>(key, t, new TimeSpan(1, 0, 0));
            redis.Dispose();
            return item; 
        }

        /// <summary>  
        /// 设置单体  
        /// </summary> 
        /// <typeparam name="T"></typeparam>   
        /// <param name="key"></param>      
        /// <param name="t"></param>             
        /// <param name="timeSpan"></param>     
        /// <returns></returns>                 
        public static bool Item_Set<T>(string key, T t, TimeSpan expiresIn)
        {
            IRedisClient redis = prcm.GetClient();
            var item = redis.Set<T>(key, t, expiresIn);
            redis.Dispose();
            return item;              
        }  

        /// <summary> 
        /// 获取单体     
        /// </summary>     
        /// <typeparam name="T"></typeparam>  
        /// <param name="key"></param>  
        /// <returns></returns>  
        public static T Item_Get<T>(string key) where T : class
        {
            IRedisClient redis = prcm.GetClient();
            var item = redis.Get<T>(key);
            redis.Dispose();
            return item;
        }

        /// <summary>  
        /// 移除单体 
        /// </summary> 
        /// <param name="key"></param> 
        public static bool Item_Remove(string key)
        {
            IRedisClient redis = prcm.GetClient();
            var item = redis.Remove(key);
            redis.Dispose();
            return item;
        }


        /// <summary>  
        /// 检查是否存在  
        /// </summary>  
        /// <param name="key"></param> 
        public static bool ContainsKey(string key)
        {
            IRedisClient redis = prcm.GetClient();
            var item = redis.ContainsKey(key);
            redis.Dispose();
            return item;
        }

        /// <summary>     
        /// 查询存在的对象  
        /// </summary>  
        /// <param name="key"></param> 
        public static List<T> GetItemsByType<T>()
        {
            IRedisClient redis = prcm.GetClient();
            var items = redis.GetTypedClient<T>();
            var itemList = items.GetAll().ToList();
            redis.Dispose();
            return itemList;
        }

        /// <summary>     
        /// 查询存在的对象数量  
        /// </summary>  
        /// <param name="key"></param> 
        public static int GetItemsSumByType<T>()
        {
            IRedisClient redis = prcm.GetClient();
            var items = redis.GetTypedClient<T>();
            var itemList = items.GetAll().ToList();
            redis.Dispose();
            return itemList.Count;
        }

        /// <summary>     
        /// 查询所有的Keys  
        /// </summary>  
        public static List<string> GetAllKeys()
        {
            IRedisClient redis = prcm.GetClient();
            var items = redis.GetAllKeys();
            redis.Dispose();
            return items;
        }
        #endregion 

        #region -- List -- 
        public static void List_Add<T>(string key, T t)
        {
            IRedisClient redis = prcm.GetClient();
            var redisTypedClient = redis.GetTypedClient<T>();
            redisTypedClient.AddItemToList(redisTypedClient.Lists[key], t);
        }

        public static bool List_Remove<T>(string key, T t)
        {
            IRedisClient redis = prcm.GetClient();
            var redisTypedClient = redis.GetTypedClient<T>(); 
            var item = redisTypedClient.RemoveItemFromList(redisTypedClient.Lists[key], t) > 0;
            redis.Dispose();
            return item;
        }

        public static void List_RemoveAll<T>(string key)
        {
            IRedisClient redis = prcm.GetClient();
            var redisTypedClient = redis.GetTypedClient<T>();
            redisTypedClient.Lists[key].RemoveAll();
        }  

        public static long List_Count(string key)
        {
            IRedisClient redis = prcm.GetClient();
            var item = redis.GetListCount(key);
            redis.Dispose();
            return item;
        }

        public static List<T> List_GetRange<T>(string key, int start, int count)
        {
            IRedisClient redis = prcm.GetClient();
            var c = redis.GetTypedClient<T>(); 
            var item = c.Lists[key].GetRange(start, start + count - 1);
            redis.Dispose();
            return item;
        }

        public static List<T> List_GetList<T>(string key)
        {
            IRedisClient redis = prcm.GetClient();
            var c = redis.GetTypedClient<T>(); 
            var item = c.Lists[key].GetRange(0, c.Lists[key].Count);
            redis.Dispose();
            return item;
        } 

        public static List<T> List_GetList<T>(string key, int pageIndex, int pageSize)
        { 
            int start = pageSize * (pageIndex - 1); 
            return List_GetRange<T>(key, start, pageSize); 
        }  

        /// <summary>  
        /// 设置缓存过期  
        /// </summary>    
        /// <param name="key"></param> 
        /// <param name="datetime"></param> 
        public static void List_SetExpire(string key, DateTime datetime)
        {
            IRedisClient redis = prcm.GetClient();
            redis.ExpireEntryAt(key, datetime);
            redis.Dispose();
        }

        #endregion

        #region -- Set --

        public static void Set_Add<T>(string key, T t)
        {
            IRedisClient redis = prcm.GetClient();
            var redisTypedClient = redis.GetTypedClient<T>();
            redisTypedClient.Sets[key].Add(t);
        }

        public static bool Set_Contains<T>(string key, T t)
        {
            IRedisClient redis = prcm.GetClient();
            var redisTypedClient = redis.GetTypedClient<T>();
            var item = redisTypedClient.Sets[key].Contains(t);
            redis.Dispose();
            return item;
        }

        public static bool Set_Remove<T>(string key, T t)
        {
            IRedisClient redis = prcm.GetClient();
            var redisTypedClient = redis.GetTypedClient<T>();  
            var item = redisTypedClient.Sets[key].Remove(t);
            redis.Dispose();
            return item;
        }

        #endregion

        #region -- Hash --

        /// <summary> 
        /// 判断某个数据是否已经被缓存 
        /// </summary> 
        /// <typeparam name="T"></typeparam>  
        /// <param name="key"></param>     
        /// <param name="dataKey"></param>    
        /// <returns></returns>        
        public static bool Hash_Exist<T>(string key, string dataKey)
        {
            IRedisClient redis = prcm.GetClient();
            var item = redis.HashContainsEntry(key, dataKey);
            redis.Dispose();
            return item;
        }

        /// <summary>  
        /// 存储数据到hash表   
        /// </summary>   
        /// <typeparam name="T"></typeparam>  
        /// <param name="key"></param>  
        /// <param name="dataKey"></param> 
        /// <returns></returns>  
        public static bool Hash_Set<T>(string key, string dataKey, T t)
        {
            IRedisClient redis = prcm.GetClient();
            string value = ServiceStack.Text.JsonSerializer.SerializeToString<T>(t);  
            var item = redis.SetEntryInHash(key, dataKey, value);
            redis.Dispose();
            return item;
        }

        /// <summary>  
        /// 移除hash中的某值  
        /// </summary>  
        /// <typeparam name="T"></typeparam> 
        /// <param name="key"></param>  
        /// <param name="dataKey"></param> 
        /// <returns></returns>    
        public static bool Hash_Remove(string key, string dataKey)
        {
            IRedisClient redis = prcm.GetClient();
            var item = redis.RemoveEntryFromHash(key, dataKey);
            redis.Dispose();
            return item;
        }

        /// <summary>  
        /// 移除整个hash  
        /// </summary> 
        /// <typeparam name="T"></typeparam> 
        /// <param name="key"></param>     
        /// <param name="dataKey"></param> 
        /// <returns></returns> 
        public static bool Hash_Remove(string key)
        {
            IRedisClient redis = prcm.GetClient();
            var item = redis.Remove(key);
            redis.Dispose();
            return item;
        }

        /// <summary> 
        /// 从hash表获取数据 
        /// </summary>  
        /// <typeparam name="T"></typeparam> 
        /// <param name="key"></param> 
        /// <param name="dataKey"></param>  
        /// <returns></returns> 
        public static T Hash_Get<T>(string key, string dataKey)
        {
            using (IRedisClient redis = prcm.GetClient())
            {         
                string value = redis.GetValueFromHash(key, dataKey);  
                return ServiceStack.Text.JsonSerializer.DeserializeFromString<T>(value); 
            }
        }

        /// <summary>  
        /// 获取整个hash的数据  
        /// </summary>   
        /// <typeparam name="T"></typeparam>   
        /// <param name="key"></param>  
        /// <returns></returns> 

        public static List<T> Hash_GetAll<T>(string key)
        {
            List<T> result = new List<T>();
            IRedisClient redis = prcm.GetClient();
            var list = redis.GetHashValues(key);  
            if (list != null && list.Count > 0)
            {
                foreach (var item in list)
                {  
                    var value = ServiceStack.Text.JsonSerializer.DeserializeFromString<T>(item);   
                    result.Add(value); 
                }
                redis.Dispose();   
            }
            return result;
        }

        /// <summary>  
        /// 设置缓存过期 
        /// </summary>  
        /// <param name="key"></param> 
        /// <param name="datetime"></param>  
        public static void Hash_SetExpire(string key, DateTime datetime)
        {
            IRedisClient redis = prcm.GetClient();
            redis.ExpireEntryAt(key, datetime);
            redis.Dispose();
        }

        #endregion
        #region -- SortedSet --

        /// <summary> 
        ///  添加数据到 SortedSet   
        /// </summary>   
        /// <typeparam name="T"></typeparam>  
        /// <param name="key"></param>  
        /// <param name="t"></param>  
        /// <param name="score"></param>   
        public static bool SortedSet_Add<T>(string key, T t, double score)
        {
            IRedisClient redis = prcm.GetClient();
            string value = ServiceStack.Text.JsonSerializer.SerializeToString<T>(t);
            var item = redis.AddItemToSortedSet(key, value, score);
            redis.Dispose();
            return item;
        }

        /// <summary> 
        /// 移除数据从SortedSet  
        /// </summary>    
        /// <typeparam name="T"></typeparam>  
        /// <param name="key"></param>  
        /// <param name="t"></param>  
        /// <returns></returns>   
        public static bool SortedSet_Remove<T>(string key, T t)
        {
            IRedisClient redis = prcm.GetClient();
            string value = ServiceStack.Text.JsonSerializer.SerializeToString<T>(t);
            var item = redis.RemoveItemFromSortedSet(key, value);
            redis.Dispose();
            return item;
        }

        /// <summary> 
        /// 修剪SortedSet  
        /// </summary>   
        /// <param name="key"></param>  
        /// <param name="size">保留的条数</param>  
        /// <returns></returns>  
        public static long SortedSet_Trim(string key, int size)
        {
            IRedisClient redis = prcm.GetClient();
            var item = redis.RemoveRangeFromSortedSet(key, size, 9999999);
            redis.Dispose();
            return item;
        }

        /// <summary> 
        /// 获取SortedSet的长度   
        /// </summary>          
        /// <param name="key"></param>  
        /// <returns></returns>    
        public static long SortedSet_Count(string key)
        {
            IRedisClient redis = prcm.GetClient();
            var item = redis.GetSortedSetCount(key);
            redis.Dispose();
            return item;
        }

        /// <summary> 
        /// 获取SortedSet的分页数据  
        /// </summary>  
        /// <typeparam name="T"></typeparam>  
        /// <param name="key"></param>  
        /// <param name="pageIndex"></param>  
        /// <param name="pageSize"></param>  
        /// <returns></returns>  
        public static List<T> SortedSet_GetList<T>(string key, int pageIndex, int pageSize)
        {
            List<T> result = new List<T>();
            IRedisClient redis = prcm.GetClient();
            var list = redis.GetRangeFromSortedSet(key, (pageIndex - 1) * pageSize, pageIndex * pageSize - 1);

            if (list != null && list.Count > 0)
            {
                foreach (var item in list)
                {    
                    var data = ServiceStack.Text.JsonSerializer.DeserializeFromString<T>(item);   
                    result.Add(data);  
                }
            }
            return result;
        }

        /// <summary> 
        /// 获取SortedSet的全部数据  
        /// </summary>    
        /// <typeparam name="T"></typeparam>  
        /// <param name="key"></param> 
        /// <param name="pageIndex"></param> 
        /// <param name="pageSize"></param>  
        /// <returns></returns>   
        public static List<T> SortedSet_GetListALL<T>(string key)
        {
            IRedisClient redis = prcm.GetClient();
            var list = redis.GetRangeFromSortedSet(key, 0, 9999999);
            List<T> result = new List<T>();
            if (list != null && list.Count > 0)
            {
                foreach (var item in list)
                {  
                    var data = ServiceStack.Text.JsonSerializer.DeserializeFromString<T>(item);     
                    result.Add(data);
                }
            }
            return result;
        }

        /// <summary>  
        /// 设置缓存过期  
        /// </summary>  
        /// <param name="key"></param>  
        /// <param name="datetime"></param> 
        public static void SortedSet_SetExpire(string key, DateTime datetime)
        {
            IRedisClient redis = prcm.GetClient();
            redis.ExpireEntryAt(key, datetime);
        }
        #endregion
    }
}
 

第二普通缓存驱动方式

using System;
using System.Web;
using System.Collections;
using System.Web.Caching;

namespace QPCenterExpress.CoreSafe.CacheBase
{
    public class CacheHelper
    {
        /// <summary>  
        /// 获取数据缓存  
        /// </summary>  
        /// <param name="cacheKey">键</param>  
        public static object GetCache(string cacheKey)
        {
            var objCache = HttpRuntime.Cache.Get(cacheKey);
            return objCache;
        }
        /// <summary>  
        /// 设置数据缓存  
        /// </summary>  
        public static void SetCache(string cacheKey, object objObject)
        {
            var objCache = HttpRuntime.Cache;
            objCache.Insert(cacheKey, objObject);
        }
        /// <summary>  
        /// 设置数据缓存  
        /// </summary>  
        public static void SetCache(string cacheKey, object objObject, int timeout = 7200)
        {
            try
            {
                if (objObject == null) return;
                var objCache = HttpRuntime.Cache;
                //相对过期  
                //objCache.Insert(cacheKey, objObject, null, DateTime.MaxValue, timeout, CacheItemPriority.NotRemovable, null);  
                //绝对过期时间  
                objCache.Insert(cacheKey, objObject, null, DateTime.Now.AddSeconds(timeout), TimeSpan.Zero, CacheItemPriority.High, null);
            }
            catch (Exception)
            {
                //throw;  
            }
        }

        /// <summary>  
        /// 设置数据缓存  
        /// </summary>  
        public static void SetCache(string cacheKey, object objObject, TimeSpan expiresIn)
        {
            try
            {
                if (objObject == null) return;
                var objCache = HttpRuntime.Cache;
                //30秒后就到期,立即移除,没商量。绝对过期测试
                //objCache.Insert("DD", "绝对过期测试", null, DateTime.Now.AddSeconds(5), System.Web.Caching.Cache.NoSlidingExpiration); 
                绝对过期时间  
                //objCache.Insert(cacheKey, objObject, null, DateTime.Now.AddSeconds(0), expiresIn, CacheItemPriority.High, null);

                //弹性过期时间,当缓存没使用10秒就过期。滑动过期测试,注:已定为一年的缓存时间
                objCache.Insert(cacheKey, objObject, null, System.Web.Caching.Cache.NoAbsoluteExpiration, expiresIn);
            }
            catch (Exception)
            {
                //throw;  
            }
        }
        /// <summary>  
        /// 移除指定数据缓存  
        /// </summary>  
        public static void RemoveCacheByKey(string cacheKey)
        {
            var cache = HttpRuntime.Cache;
            cache.Remove(cacheKey);
        }
        /// <summary>  
        /// 移除全部缓存  
        /// </summary>  
        public static void RemoveAllCache()
        {
            var cache = HttpRuntime.Cache;
            var cacheEnum = cache.GetEnumerator();
            while (cacheEnum.MoveNext())
            {
                cache.Remove(cacheEnum.Key.ToString());
            }
        }
    }
}
 

五、内存数据库与传统数据库数据同步

缓存服务类型,CacheServiceType=1为写进队列,CacheServiceType!=1为,直接写进缓存。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using QPCenterExpress.Common;
using QPCenterExpress.Data.Connection;
using QPCenterExpress.Data.Factory;
using Newtonsoft.Json;

namespace QPCenterLogic.Common
{
    public class DataSyncCacheLogic
    {
        DataTableCache cache = new DataTableCache();
        /// <summary>
        /// 增加同步数据到缓存
        /// </summary>
        /// <param name="ParamJsonData"></param>
        /// <returns></returns>
        public string AddDataToCache(string ParamJsonData)
        {
            string table = TBase_Json.ToArray(ParamJsonData)[0].ToString();
            DataRow dr = TBase_Json.ToObject<DataRow>(TBase_Json.ToArray(ParamJsonData)[1].ToString());

            string strCacheSetSQL = QPCenterExpress.Common.AutoSelectSql.GetSql();
            DataSet ds = new DataSet();
            ds.Tables.Add(TDataSqlHelper.GetDataTableBySql(string.Format(strCacheSetSQL, table), table));

            DataSet tempDs = new DataSet();
            foreach (DataRow tempDr in ds.Tables[0].Rows)
            {
                string strAddCacheDataSQL = QPCenterExpress.Common.AutoSelectSql.GetSql(1);
                DataTable tempDt = TDataSqlHelper.GetDataTableBySql(string.Format(strAddCacheDataSQL, tempDr["FCACHE"].ToString()), table);
                string tempSql = tempDt.Rows[0]["FSQL_EXECUTE"].ToString();
                tempSql = tempSql.ToUpper();
                if (tempSql.Contains("WHERE"))
                {
                    tempSql = tempSql.Replace("WHERE", "WHERE " + tempDt.Rows[0]["FKEYFIELD"].ToString() + "'" + dr[tempDt.Rows[0]["FKEYFIELD"].ToString()].ToString() + "' and ");
                }
                else
                {
                    tempSql = tempSql + "WHERE " + tempDt.Rows[0]["FKEYFIELD"].ToString() + "'" + dr[tempDt.Rows[0]["FKEYFIELD"].ToString()].ToString() + "'";
                }

                cache.AddDataTableToCache(tempDt.Rows[0]["FCACHENAME"].ToString(), TDataSqlHelper.GetDataTableBySql(string.Format(tempSql)), tempDt.Rows[0]["FKEYFIELD"].ToString(), 2);
            }
            
            
            return TBase_Json.ToJson(ds);
        }

        /// <summary>
        /// 更新同步数据到缓存
        /// </summary>
        /// <param name="ParamJsonData"></param>
        /// <returns></returns>
        public string UpdateDataToCache(string ParamJsonData)
        {
            object[] retObjs = TBase_Json.ToArray(ParamJsonData);
            string table = retObjs[0].ToString();
            DataTable syncDt = JsonConvert.DeserializeObject<DataTable>(retObjs[1].ToString());

            string strCacheSetSQL = QPCenterExpress.Common.AutoSelectSql.GetSql();
            DataSet ds = new DataSet();
            ds.Tables.Add(TDataSqlHelper.GetDataTableBySql(string.Format(strCacheSetSQL, table), table));

            if (ds.Tables[0].Rows.Count > 0)
            {
                string strAddCacheDataSQL = QPCenterExpress.Common.AutoSelectSql.GetSql(1);
                DataTable tempDt = TDataSqlHelper.GetDataTableBySql(string.Format(strAddCacheDataSQL, ds.Tables[0].Rows[0]["FCACHE"].ToString()), table);

                DataSet tempDs = new DataSet();

                string whereStr = " ";

                foreach (DataRow dr in syncDt.Rows)
                {
                    int temProws = 0;
                    if (ds.Tables[0].Rows.Count > 1)
                    {
                        foreach (DataRow tempDr in ds.Tables[0].Rows)
                        {
                            if (temProws == 0)
                            {
                                whereStr = whereStr + tempDt.Rows[0]["FKEYFIELD"].ToString() + "='" + dr[tempDt.Rows[0]["FKEYFIELD"].ToString()].ToString() + "'";
                            }
                            else
                            {
                                whereStr = whereStr + " and " + tempDt.Rows[0]["FKEYFIELD"].ToString() + "='" + dr[tempDt.Rows[0]["FKEYFIELD"].ToString()].ToString() + "'";
                            }

                            temProws = temProws + 1;
                        }
                    }
                    else
                    {
                        whereStr = tempDt.Rows[0]["FKEYFIELD"].ToString() + "='" + dr[tempDt.Rows[0]["FKEYFIELD"].ToString()].ToString() + "'";
                    }

                    string tempSql = tempDt.Rows[0]["FSQL_EXECUTE"].ToString();
                    tempSql = tempSql.ToUpper();
                    if (tempSql.Contains("WHERE") || tempSql.Contains(" ON "))
                    {
                        //tempSql = tempSql.Replace("WHERE", "WHERE " + whereStr + "' and ");
                        tempSql = "SELECT A.* FROM(" + tempSql + ") AS A WHERE " + whereStr;
                    }
                    else
                    {
                        tempSql = tempSql + " WHERE " + whereStr;
                    }

                    DataTable queryDt = cache.GetDataTableByCache(tempDt.Rows[0]["FCACHENAME"].ToString(), tempDt.Rows[0]["FKEYFIELD"].ToString(), dr[tempDt.Rows[0]["FKEYFIELD"].ToString()].ToString());
                    if (queryDt != null & queryDt.Rows.Count > 0)
                    {
                        if (dr.RowState == DataRowState.Deleted)
                        {
                            cache.DeleteDataRowByCache(tempDt.Rows[0]["FCACHENAME"].ToString(), tempDt.Rows[0]["FKEYFIELD"].ToString(), dr[tempDt.Rows[0]["FKEYFIELD"].ToString()].ToString(), 2);
                        }
                        else
                        {
                            cache.DeleteDataRowByCache(tempDt.Rows[0]["FCACHENAME"].ToString(), tempDt.Rows[0]["FKEYFIELD"].ToString(), dr[tempDt.Rows[0]["FKEYFIELD"].ToString()].ToString(), 2);
                            cache.AddDataTableToCache(tempDt.Rows[0]["FCACHENAME"].ToString(), TDataSqlHelper.GetDataTableBySql(string.Format(tempSql)), tempDt.Rows[0]["FKEYFIELD"].ToString(), 2);
                        }
                    }
                    else
                    {
                        cache.AddDataTableToCache(tempDt.Rows[0]["FCACHENAME"].ToString(), TDataSqlHelper.GetDataTableBySql(string.Format(tempSql)), tempDt.Rows[0]["FKEYFIELD"].ToString(), 2);
                    }
                }
            }

            return TBase_Json.ToJson(ds);
        }

        /// <summary>
        /// 更新同步数据到缓存
        /// </summary>
        /// <param name="ParamJsonData"></param>
        /// <returns></returns>
        public string UpdateDelDataToCache(string ParamJsonData)
        {
            object[] retObjs = TBase_Json.ToArray(ParamJsonData);
            string table = retObjs[0].ToString();
            DataTable syncDt = JsonConvert.DeserializeObject<DataTable>(retObjs[1].ToString());

            string strCacheSetSQL = QPCenterExpress.Common.AutoSelectSql.GetSql();
            DataSet ds = new DataSet();
            ds.Tables.Add(TDataSqlHelper.GetDataTableBySql(string.Format(strCacheSetSQL, table), table));

            if (ds.Tables[0].Rows.Count > 0)
            {
                string strAddCacheDataSQL = QPCenterExpress.Common.AutoSelectSql.GetSql(1);
                DataTable tempDt = TDataSqlHelper.GetDataTableBySql(string.Format(strAddCacheDataSQL, ds.Tables[0].Rows[0]["FCACHE"].ToString()), table);
                foreach (DataRow dr in syncDt.Rows)
                {
                    cache.DeleteDataRowByCache(tempDt.Rows[0]["FCACHENAME"].ToString(), tempDt.Rows[0]["FKEYFIELD"].ToString(), dr[tempDt.Rows[0]["FKEYFIELD"].ToString()].ToString(), 2);                    
                }
            }

            return TBase_Json.ToJson(ds);
        }

        /// <summary>
        /// 删除同步数据到缓存
        /// </summary>
        /// <param name="ParamJsonData"></param>
        /// <returns></returns>
        public string DelDataToCache(string ParamJsonData)
        {
            object[] retObjs = TBase_Json.ToArray(ParamJsonData);
            string table = retObjs[0].ToString();
            string fkey = retObjs[1].ToString();
            string fvalue = retObjs[2].ToString();

            string strCacheSetSQL = QPCenterExpress.Common.AutoSelectSql.GetSql();
            DataTable tempDt = TDataSqlHelper.GetDataTableBySql(string.Format(strCacheSetSQL, table), table);

            bool isDel = cache.DeleteDataRowByCache(tempDt.Rows[0]["FCACHE"].ToString(), fkey, fvalue, 2);
            return TBase_Json.ToJson(isDel);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="ParamJsonData"></param>
        /// <returns></returns>
        public string AddReportStatusToCache(string ParamJsonData)
        {
            object[] retObjs = TBase_Json.ToArray(ParamJsonData);
            string tableName = retObjs[0].ToString();
            DataTable reportStatusDt = JsonConvert.DeserializeObject<DataTable>(retObjs[1].ToString());
            string tableFKEYFIELD = retObjs[2].ToString();
            bool isAdd = cache.AddDataTableToCache(tableName, reportStatusDt, tableFKEYFIELD, 2);
       //     DataTable tempDt = cache.GetDataTableByCache(tableName);
            return TBase_Json.ToJson(isAdd);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="ParamJsonData"></param>
        /// <returns></returns>
        public string DelReportStatusToCache(string ParamJsonData)
        {
            object[] retObjs = TBase_Json.ToArray(ParamJsonData);
            string tableName = retObjs[0].ToString();
            string fkey = retObjs[1].ToString();
            string fvalue = retObjs[2].ToString();
            bool isDel = cache.DeleteDataRowByCache(tableName, fkey, fvalue, 2);
            return TBase_Json.ToJson(isDel);
        }

    }
}
 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值