c#中的Cache缓存技术

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

2、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里有很几种重载

参数一:引用该对象的缓存键

参数二:要插入缓存中的对象

参数三:缓存键的依赖项,NoSlidingExpiration

4.一般什么时候选用cache

cache一般用于数据较固定,访问较频繁的地方,例如在前端进行分页的时候,初始化把数据放入缓存中,然后每次分页都从缓存中取数据,这样减少了连接数据库的次数,提高了系统的性能。

    /// <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,  new TimeSpan(0, 0, timeout), CacheItemPriority.NotRemovable, null);  
            //绝对过期时间  
            objCache.Insert(cacheKey, objObject, null, DateTime.UtcNow.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());  
        }  
    }