在我看到的所有示例中 like this , 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
});
}
}
最佳答案
我使用了这个扩展,但是你失去了基于请求上下文的优化。 (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; }
}
}
关于使用 ServiceStack + Redis : How to not return System. 对象缓存并返回 DTO?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18414418/