ObjectCache不缓存json数据

时间:2014-01-04 09:46:43

标签: c# c#-4.0 caching

我正在尝试缓存一些作为Json返回的数据,问题是我的缓存似乎没有缓存数据而且我不知道为什么,任何人都可以看看我的代码并让新手知道他在哪里出了问题。

public class GetTravelAdvice : ITravelAdvice
{
    private static readonly string Key = ConfigurationManager.AppSettings["FCO_URL"];

    public async Task<IEnumerable<TravelAdvice>> GetFcoTravelAdvice(string country)
    {
        using (var ta = new HttpClient())
        {
            string cacheDataTravelAdvice = "FCOLocation" + RegexHelpers.RegexRemoveAllInvalidCharactersKeepWhiteSpace(country.ToLower());

            ObjectCache travelCache = MemoryCache.Default;
            var objectInCache       = travelCache.Get(cacheDataTravelAdvice) as IEnumerable<TravelAdvice>;

            if (objectInCache != null)
                return objectInCache.AsEnumerable();


            string ensureCountryStringIsValid = RegexHelpers.RegexRemoveAllInvalidCharactersKeepWhiteSpace(country);
            var url = await ta.GetStringAsync(string.Format("{0}{1}{2}", Key, HttpUtility.HtmlEncode(ensureCountryStringIsValid), ".json")).ConfigureAwait(false);

            var policy = new CacheItemPolicy { AbsoluteExpiration = DateTime.Now.AddMinutes(15) };

            travelCache.Add(cacheDataTravelAdvice, url, policy);

            return new[] { JsonConvert.DeserializeObject<TravelAdvice>(url) };
        }
    }
}

感谢您的帮助

1 个答案:

答案 0 :(得分:3)

在这一行,url变量是一个字符串实例,对吗?

var url = await ta.GetStringAsync(string.Format("{0}{1}{2}", Key, HttpUtility.HtmlEncode(ensureCountryStringIsValid), ".json")).ConfigureAwait(false);

这是您在缓存中存储的内容:string值:

travelCache.Add(cacheDataTravelAdvice, url, policy);

在这里:

var objectInCache = travelCache.Get(cacheDataTravelAdvice) as IEnumerable<TravelAdvice>;

您正试图将其投放到IEnumerable<TravelAdvice>。通常情况下,如果您在缓存中存储了一个字符串,则无法从中获取IEnumerable<TravelAdvice>

所以你需要把它读成字符串:

string objectInCache = travelCache.Get(cacheDataTravelAdvice) as string;

然后将其反序列化为基础对象:

if (objectInCache != null)
{
    return new[] { JsonConvert.DeserializeObject<TravelAdvice>(objectInCache) };
}

另一种可能性是将IEnumerable<TravelAdvice>实例直接存储到缓存中:

var url = await ta.GetStringAsync(string.Format("{0}{1}{2}", Key, HttpUtility.HtmlEncode(ensureCountryStringIsValid), ".json")).ConfigureAwait(false);
var data = new[] { JsonConvert.DeserializeObject<TravelAdvice>(url) };
travelCache.Add(cacheDataTravelAdvice, data, policy);
return data;