Cache缓存优化

 1 降低数据库压力
 2 <appSettings><add key="ModelCache" value="1"/></appSettings> //设置实体缓存时间
 3 
 4     public RupengWang.Model.Course GetModelByCache(long Id)
 5     {
 6         string CacheKey = "CourseModel-" + Id;
 7         object objModel = Maticsoft.Common.DataCache.GetCache(CacheKey);
 8         if (objModel == null)
 9         {
10             objModel = dal.GetModel(Id);
11             if (objModel != null)
12             {
13                 int ModelCache = Maticsoft.Common.ConfigHelper.GetConfigInt("ModelCache");
14                 Maticsoft.Common.DataCache.SetCache(CacheKey, objModel, DateTime.Now.AddMinutes(ModelCache), TimeSpan.Zero);
15             }
16         }
17         return (RupengWang.Model.Course)objModel;
18     }

2.MVC中缓存

 1 /// <summary>
 2         /// 从缓存中获得自定义匿名对象
 3         /// </summary>
 4         /// <returns></returns>
 5         public object GetModelByCache()
 6         {
 7             string CacheKey = "MyProductAndGroupModel_";
 8             object objModel = HttpRuntime.Cache[CacheKey]; //获得当前应用程序的缓存
 9             if (objModel == null)
10             {
11                 objModel = GetDefineModelByEdm();
12                 if (objModel != null)
13                 {
14                     //int ModelCache = Convert.ToInt32(ConfigurationManager.AppSettings["ModelCache"]);
15                     HttpRuntime.Cache.Insert(CacheKey, objModel, null, DateTime.Now.AddMinutes(2), TimeSpan.Zero);
16                 }
17             }
18             return objModel;
19         }

3 WebForm中所写最简单的缓存:

public partial class WebForm_cache : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            #region 缓存
            List<object> list = (List<object>)HttpRuntime.Cache["tc_students"];
            if (list == null || list.Count <= 0) //如果缓存中没有就从DB中获取
            {
                List<object> listDB = new MyORM_BLL().SelectAllModel(typeof(TC_STUDENT));
                if (listDB.Count > 0) //把数据库中获得的数据进行缓存
                {
                    HttpRuntime.Cache.Insert("tc_students", listDB, null, DateTime.Now.AddSeconds(30), TimeSpan.Zero);
                }
                list = listDB;
            }
            Repeater1.DataSource = list;
            Repeater1.DataBind(); 
            #endregion
        }
    }

WebForm_cache.aspx.cs

参考:

http://www.cnblogs.com/zgx/archive/2009/03/16/1413643.html

http://bbs.csdn.net/topics/310107146

原文地址:https://www.cnblogs.com/adolphyang/p/4727025.html