.NET Core 2.0遷移技巧之MemoryCache問題修復


對於傳統的.NET Framework項目而言,System.Runtime.Caching命名空間是常用的工具了,其中MemoryCache類則常被用於實現內存緩存。

.NET Core 2.0暫時還不支持System.Runtime.Caching dll,這也就意味着MemoryCache相關代碼不再起作用了。

但是好消息是,我們可以使用.NET Core 2.0的新API實現內存緩存功能,簡單修改代碼,解決不兼容問題。

 

解決方案


 

  1.將舊代碼導入項目中,如下:

 

using System;
using System.Runtime.Caching;

namespace TestWebApp.Service
{
    public class MemoryCacheService
    {
        static ObjectCache cache = MemoryCache.Default;
        /// <summary>
        /// 獲取緩存值
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        private object GetCacheValue(string key)
        {
            if (key != null && cache.Contains(key))
            {
                return cache[key];
            }
            return default(object);
        }
        /// <summary>
        /// 添加緩存內容
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public static void SetChacheValue(string key, object value)
        {
            if (key != null)
            {
                CacheItemPolicy policy = new CacheItemPolicy
                {
                    SlidingExpiration = TimeSpan.FromHours(1)
                    
                };
                cache.Set(key, value, policy);
            }
        }
    }
}

 

  導入后你會發現VS會提示無法找到System.Runtime.Caching命名空間,原有的代碼無法直接編譯使用。

 

  2.添加對Microsoft.Extensions.Caching.Memory命名空間的引用,它提供了.NET Core默認實現的MemoryCache類,以及全新的內存緩存API

  

using Microsoft.Extensions.Caching.Memory;

 

  3.改寫代碼,使用新的API實現內存緩存功能

  初始化緩存對象方式改寫前:

static ObjectCache cache = MemoryCache.Default;

 

  初始化緩存對象方式改寫后:

static MemoryCache cache = new MemoryCache(new MemoryCacheOptions());

 

  讀取內存緩存值方式變化:

private object GetCacheValue(string key)
{
    if (key != null && cache.Contains(key))
    {
        return cache[key];
    }
    return default(object);
}

 

  改寫后:

private object GetCacheValue(string key)
{
    object val = null;
    if (key != null && cache.TryGetValue(key, out val))
    {
        return val;
    }
    else
    {
        return default(object);
    }
}

 

  設定內存緩存內容方式變化:

public static void SetChacheValue(string key, object value)
{
    if (key != null)
    {
        CacheItemPolicy policy = new CacheItemPolicy
        {
            SlidingExpiration = TimeSpan.FromHours(1)
        };
        cache.Set(key, value, policy);
    }
}

 

  修改后:

 public static void SetChacheValue(string key, object value)
{
    if (key != null)
    {
        cache.Set(key, value, new MemoryCacheEntryOptions
        {
            SlidingExpiration = TimeSpan.FromHours(1)
        });
    }
}

 

結論


 

在使用了Microsoft.Extensions.Caching.Memory下的新API改寫了舊代碼后,你會發現原有的各種內存緩存超時策略全都是有對應新API的,包括AbsoluteExpiration, SlidingExpiration等等。

所以我們還是可以很輕松的使用.NET Core新API簡單改動下下就能重用現有絕大部分舊代碼,將其遷移過來繼續起作用。

 

遷移后的完整代碼如下:

using Microsoft.Extensions.Caching.Memory;
using System;

namespace TestMemoryCacheWebApp.Services
{
    public class MemoryCacheService
    {
        static MemoryCache cache = new MemoryCache(new MemoryCacheOptions());
        /// <summary>
        /// 獲取緩存值
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        private object GetCacheValue(string key)
        {
            object val = null;
            if (key != null && cache.TryGetValue(key, out val))
            {

                return val;
            }
            else
            {
                return default(object);
            }
        }
        /// <summary>
        /// 添加緩存內容
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public static void SetChacheValue(string key, object value)
        {
            if (key != null)
            {
                cache.Set(key, value, new MemoryCacheEntryOptions
                {
                    SlidingExpiration = TimeSpan.FromHours(1)
                });
            }
        }
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM