ASP.NET cache缓存的用法




本文导读:在.NET运用中经常用到缓存(Cache)对象。有HttpContext.Current.Cache以及HttpRuntime.Cache,HttpRuntime.Cache是应用程序级别的,而HttpContext.Current.Cache是针对当前WEB上下文定义的。HttpRuntime下的除了WEB中可以使用外,非WEB程序也可以使用。

1、HttpRuntime.Cache 相当于就是一个缓存具体实现类,这个类虽然被放在了 System.Web 命名空间下了。但是非 Web 应用也是可以拿来用的。


2、HttpContext.Cache 是对上述缓存类的封装,由于封装到了 HttpContext ,局限于只能在知道 HttpContext 下使用,即只能用于 Web 应用。

综上所属,在可以的条件,尽量用 HttpRuntime.Cache ,而不是用 HttpContext.Cache 。

 

一、有以下几条缓存数据的规则


第一,数据可能会被频繁的被使用,这种数据可以缓存。


第二,数据的访问频率非常高,或者一个数据的访问频率不高,但是它的生存周期很长,这样的数据最好也缓存起来。


第三是一个常常被忽略的问题,有时候我们缓存了太多数据,通常在一台X86的机子上,如果你要缓存的数据超过800M的话,就会出现内存溢出的错误。所以说缓存是有限的。换名话说,你应该估计缓存集的大小,把缓存集的大小限制在10以内,否则它可能会出问题。在Asp.net中,如果缓存过大的话也会报内存溢出错误,特别是如果缓存大的DataSet对象的时候。

你应该认真分析你的程序。根据实际情况来看哪里该用,哪里不该用。如:cache用得过多也会增大服务器的压力。整页输出缓存,又会影响数据的更新。 如果真的需要缓存很大量的数据,可以考虑静态技术。

 

二、下面介绍HttpRuntime.Cache常用方法

 

C# 代码 
<strong>using System;
using System.Web;
using System.Collections;

public class CookiesHelper
    {
    /** <summary>
    /// 获取数据缓存
    /// </summary>
    /// <param name="CacheKey">键</param>
    public static object GetCache(string CacheKey)
    {
        System.Web.Caching.Cache objCache = HttpRuntime.Cache;
        return objCache[CacheKey];
    }

    /** <summary>
    /// 设置数据缓存
    /// </summary>
    public static void SetCache(string CacheKey, object objObject)
    {
        System.Web.Caching.Cache objCache = HttpRuntime.Cache;
        objCache.Insert(CacheKey, objObject);
    }

    /** <summary>
    /// 设置数据缓存
    /// </summary>
    public static void SetCache(string CacheKey, object objObject, TimeSpan Timeout)
    {
        System.Web.Caching.Cache objCache = HttpRuntime.Cache;
        objCache.Insert(CacheKey, objObject, null, DateTime.MaxValue, Timeout, System.Web.Caching.CacheItemPriority.NotRemovable, null);
    }

    /** <summary>
    /// 设置数据缓存
    /// </summary>
    public static void SetCache(string CacheKey, object objObject, DateTime absoluteExpiration, TimeSpan slidingExpiration)
    {
        System.Web.Caching.Cache objCache = HttpRuntime.Cache;
        objCache.Insert(CacheKey, objObject, null, absoluteExpiration, slidingExpiration);
    }

    /** <summary>
    /// 移除指定数据缓存
    /// </summary>
    public static void RemoveAllCache(string CacheKey)
    {
        System.Web.Caching.Cache _cache = HttpRuntime.Cache;
        _cache.Remove(CacheKey);
    }

    /** <summary>
    /// 移除全部缓存
    /// </summary>
    public static void RemoveAllCache()
    {
        System.Web.Caching.Cache _cache = HttpRuntime.Cache;
        IDictionaryEnumerator CacheEnum = _cache.GetEnumerator();
        while (CacheEnum.MoveNext())
        ...{
            _cache.Remove(CacheEnum.Key.ToString());
        }
    }
}
</strong>
三、实战,个人项目
1、第一步,在global.asax 加入
<strong>    void Application_Start(object sender, EventArgs e)
    {
        // 在应用程序启动时运行的代码
        try
        {
            //定义连接字符串
            string conStr = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            System.Data.SqlClient.SqlDependency.Start(conStr);//启动监听服务,ps:只需启动一次
            System.Web.Caching.SqlCacheDependencyAdmin.EnableNotifications(conStr);//设置通知的数据库连接,ps:只需设置一次
            string[] str = { "TMS_OptionScoreDetails", "TMS_TeachAssess", "TMS_TeachAssessDetail", "TMS_TeachAssessPublish", "TMS_TeachAssessRecord", "TMS_TeachAssessRecordDetails", "TMS_TeachOption" };
            System.Web.Caching.SqlCacheDependencyAdmin.EnableTableForNotifications(conStr, str);//设置通知的数据库连接和表,ps:只需设置一次


        }
        catch
        {

        }
    }
</strong>
2、第二步,在引用缓存类,并在项目用应用。
          //缓存
            DataSet myDataSet = new DataSet();

            string CacheKey = "SearchDate" + TeachAssessID;
            object objModel = TMSCommonMethod.GetCache(CacheKey);//从缓存中获取
            if (objModel == null)//缓存里没有
            {
                TMSTeachAssessDetailManager myTMSTeachAssessDetailManager = new TMSTeachAssessDetailManager();
                TMSTeachAssessDetailQuery myTMSTeachAssessDetailQuery = new TMSTeachAssessDetailQuery();
                //myTMSTeachAssessDetailQuery.TeachAssessPublishID = TeachAssessPublishID;
                myTMSTeachAssessDetailQuery.TeachAssessID = TeachAssessID;
                myDataSet = myTMSTeachAssessDetailManager.SearchDate(null, myTMSTeachAssessDetailQuery);

                objModel = myDataSet;//把数据存入缓存
                if (objModel != null)
                {
                    
                    System.Web.Caching.SqlCacheDependency dep = new System.Web.Caching.SqlCacheDependency(ConfigurationManager.AppSettings["CacheDataBaseName"].ToString(), TMSTeachAssessDetail.TABLENAME);
                    TMSCommonMethod.SetCache(CacheKey, objModel, dep);//写入缓存
                }
            }
            else
            {
                myDataSet = (DataSet)objModel;
            }



  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

三天不学习

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值