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());  
        }  
    }  
相關文章
相關標籤/搜索