使用 ServiceStack + Redis : How to not return System. 对象缓存并返回 DTO?

标签 caching redis servicestack

在我看到的所有示例中 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/

相关文章:

javascript - 是否可以用 HTML 替换客户端缓存的文件

asp.net-mvc - 提供者必须实现类 'System.Web.SessionState.SessionStateStoreProviderBase'

amazon-web-services - 强制 Terraform 在 AWS Elasticache Redis 集群上应用待处理的更改

c# - 处理 servicestack Html5ModeFeature 插件中的任何默认文档类型

c# - ServiceStack.Text 和 ISODate ("")

RedisMQ PriorityQueue 中的 Servicestack 内部优先级

Symfony 缓存组件 - Redis 适配器

java - Spring Cache - 使用自定义键更改其他缓存方法后,如何获取所有实际数据实体的列表?

css - 我如何确定并确定我的网页未被缓存?

macos - 如何在 mac os 10.13 上安装 php-redis 扩展?