c#中的Cache缓存技术

一、HttpRuntime.Cache 至关于就是一个缓存具体实现类,这个类虽然被放在了 System.Web 命名空间下了。可是非 Web 应用也是能够拿来用的。前端

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

综上所属,在能够的条件,尽可能用 HttpRuntime.Cache ,而不是用 HttpContext.Cache 。 缓存

Cache有如下几条缓存数据的规则。
第一,数据可能会被频繁的被使用,这种数据能够缓存。
第二,数据的访问频率很是高,或者一个数据的访问频率不高,可是它的生存周期很长,这样的数据最好也缓存起来。
第三是一个经常被忽略的问题,有时候咱们缓存了太多数据,一般在一台X86的机子上,若是你要缓存的数据超过800M的话,就会出现内存溢出的错误。因此说缓存是有限的。换名话说,你应该估计缓存集的大小,把缓存集的大小限制在10之内,不然它可能会出问题。性能

1.cache的建立
   cache.Insert(string key,object value,CacheDependency dependencies,DateTime absoluteExpiration,TimeSpan slidingExpiration)//只介绍有5个参数的状况,其实cache里有很几种重载
参数一:引用该对象的缓存键
参数二:要插入缓存中的对象
参数三:缓存键的依赖项,当任何依赖项更改时,该对象即无效,并从缓存中移除。 null.">若是没有依赖项,则此参数包含 null。
参数四:设置缓存过时时间
参数五:参数四的依赖项,若是使用绝对到期,null.">slidingExpiration parameter must beNoSlidingExpiration.">则 slidingExpiration 参数必须为 
NoSlidingExpirationui

2.销毁cache
cache.Remove(string key)//key为缓存键,经过缓存键进行销毁
3.调用cache
例如你存的是一个DataTable对象,调用以下: DataTable finaltable = Cache["dt"] as DataTable;
4.通常何时选用cache
cache通常用于数据较固定,访问较频繁的地方,例如在前端进行分页的时候,初始化把数据放入缓存中,而后每次分页都从缓存中取数据,这样减小了链接数据库的次数,提升了系统的性能。
this

    /// <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 RemoveAllCache(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());  
        }  
    }  
相关文章
相关标签/搜索