0

我刚刚实现了我的Asp.Net Web API控制器的输出缓存,使用连接到StackExchange.Redis libraryStrathWeb's library连接到Azure托管的Redis缓存。CacheOutput属性忽略Azure托管的Redis缓存

我写了一个自定义类,实现StrathWeb IApiOutputCache interface并调用等效的StackExchange方法。这被注册为Global.asax.cs中的缓存输出提供程序。

下面是使用的例子:

public class MyApiController : ApiController 
{ 
    private const int FIFTEEN_MINUTES_IN_SECONDS = 900; 

    [CacheOutput(ClientTimeSpan = FIFTEEN_MINUTES_IN_SECONDS, ServerTimeSpan = FIFTEEN_MINUTES_IN_SECONDS)] 
    async public Task<Data> GetAsync(int param1, string param2) 
    { 
    return await GetExpensiveData(); 
    } 

    [Serializable] 
    public class Data 
    { 
    // Members omitted for brevity 
    } 
} 

当呼叫到API端点,我可以看到,该框架正确调用我的IApiOutputCache类所需的所有方法制成的:包含,设置和获取。但是,即使找到并返回了缓存副本,也会始终运行GetExpensiveData()方法并返回“新鲜”数据。

没有错误发生。缓存似乎正在工作。然而,我的昂贵的代码总是被调用。

感谢您的帮助:)。

+3

你可以分享你的IApiOutputCache Redis实现吗? – tuler 2015-02-01 15:50:14

回答

1

问题已解决。我错误地从我的IApiOutputCache类调用Redis。

之前...

public class AzureRedisApiOutputCache : IApiOutputCache 
{ 
    public object Get(string key) 
    { 
    return AzureRedisCache.Instance.GetDatabase().StringGet(key); 
    } 
} 

后...

public class AzureRedisApiOutputCache : IApiOutputCache 
{ 
    public object Get(string key) 
    { 
    // Call the extension method that also performs deserialization... 
    return AzureRedisCache.Instance.GetDatabase().Get(key); 
    } 
} 

public static class RedisDatabaseExtensions 
{ 
    public static object Get(this IDatabase cache, string key) 
    { 
     return Deserialize<object>(cache.StringGet(key)); 
    } 
} 

这严重地混淆了我一段时间,因为CacheOutput框架从未报告错误。它只是默默地失败了,并回到了控制器方法。