1

在我看到的所有这样的示例,ServiceStack 方法中的缓存必须具有 System.Object 的返回类型。是否有允许返回正常 DTO 的更新/更新的文档?

例如,如果这个 Get 方法不返回“对象”(从 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
            });
    }
}
4

1 回答 1

2

我使用这个扩展,但是你失去了基于请求上下文的优化。(json、压缩等)

public static class ICacheClientExtensions
{
    public static T ToResultUsingCache<T>(this ICacheClient cache, string cacheKey, Func<T> fn, int hours = 1) where T : class
    {
        var cacheResult = cache.Get<T>(cacheKey);
        if (cacheResult != null)
        {
            return cacheResult;
        }
        var result = fn();
        if (result == null) return null;
        cache.Set(cacheKey, result, TimeSpan.FromHours(hours));
        return result;
    } 
}

public class MyService : Service
{
    public Data Get(GetData request)
    {
        var key = UrnId.Create<Data>(request.Id);

        Func<Data> fn = () => Db.GetData(request.Id);

        return Cache.ToResultUsingCache(key, fn);
    }

    [Route("/data/{id}")]
    public class GetData: IReturn<Data>
    {
        public int Id{ get; set; }
    }
}
于 2013-08-28T22:45:25.287 回答