ServiceStack:如何判断请求的返回是否被缓存?

时间:2013-08-30 19:46:02

标签: c# caching servicestack

我已经在我的请求中连接了缓存,但是我希望能够判断我返回的返回是否实际上来自缓存。有没有办法看到这个?我可以访问代码库进行修改。

ServiceStack的标准缓存模式:

public class OrdersService : Service
{
    public object Get(CachedOrders request)
    {
        var cacheKey = "unique_key_for_this_request";
        return base.RequestContext.ToOptimizedResultUsingCache(base.Cache,cacheKey,()=> 
            {
                //Delegate is executed if item doesn't exist in cache 
                //Any response DTO returned here will be cached automatically
            });
    }
}

1 个答案:

答案 0 :(得分:3)

如您的注释中所述,只有在缓存中不存在该项时,才会执行传递给ToOptimizedResultUsingCache方法的委托。我只想在响应DTO中添加一个“cached at”属性,并将其设置在该委托中。

public class OrdersService : Service
{
    public object Get(CachedOrders request)
    {
        var cacheKey = "unique_key_for_this_request";
        var returnDto = base.RequestContext.ToOptimizedResultUsingCache(base.Cache,cacheKey,() => {
            return new MyReturnDto {
                CachedAt = DateTime.Now
            };                
        });
    }
}

然后,您可以使用CachedAt属性查看项目的缓存时间。

如果您不想修改DTO,则可以在缓存结果时使用调用委托范围之外的变量。

public class OrdersService : Service
{
    public object Get(CachedOrders request)
    {
        var cacheKey = "unique_key_for_this_request";
        var isCached = false;
        var returnDto = base.RequestContext.ToOptimizedResultUsingCache(base.Cache,cacheKey,() => {
            isCached = true;             
        });
        // Do something if it was cached...
    }
}
相关问题