服务栈缓存

ServiceStack Caching

我希望使用 ServiceStack 来缓存昂贵的查询。

我的思路如下

第 1 步:将整个数据库视图缓存到一天后过期的 Redis

第 2 步:当客户端调用 API 路由“/cached/balances/{Date}”时,服务仅 returns 缓存数据库视图的一个子集。

为了实现这个,我正在使用

请求和响应模型

[Route("/balances", "GET", Notes = "A call to Db which extracts the entire Db balance view")]
public class GetBalances : IReturn<GetBalancesResponse>
{

}

[Route("/cached/balances/{Date}", "GET", Notes = "Gets a subsection of cached balanced")]
public class GetCachedBalances : IReturn<GetBalancesResponse>
{
     public int Date { get; set;} 
     public int? EntityId { get; set;} 
}

public class GetBalancesResponse
{
    public List<BalanceView> Result { get; set; }
}

服务接口

 public object Any(GetBalances request)
 {
    var balances = Db.Select<BalanceView>();
    return new GetBalancesResponse {Result = balances };
 }

 public object Any(GetCachedBalances request)
 {
       GetBalances balancesRequest = request.ConvertTo<GetBalances>();

     // get the cached response
      var allBalances = (CompressedResult)base.Request.ToOptimizedResultUsingCache(
                this.CacheClient, "urn:balances", () => {
                    var service = this.ResolveService<BalanceServices>();
                    return (GetBalancesResponse)service.Any(balanceRequest);
                });

            // filter the results -> this does not work!
            var filterBalances = response.Response.ConvertTo<GetBalancesResponse>().Result.Where(Ar => Ar.Date == request.Date && (Ar.EntityId == request.EntityId || request.EntityId == null)); 

    return new GetBalancesResponse {Result = filteredBalances};
 }

余额过滤不起作用,因为我似乎无法将压缩结果转换为 ResponseDto。

我自己的问题可能有答案。

ServiceInterface GetCachedBalances 可以按以下方式过滤

  public object Any(GetCachedBalances request)
  {
     GetBalances balancesRequest = request.ConvertTo<GetBalances>();

     // cache everything
     var filteredCachedResponse = (CompressedResult)base.Request.ToOptimizedResultUsingCache(
            this.CacheClient, "urn:balances", () => {
                var service = this.ResolveService<BalanceServices>();
                return ((GetBalancesResponse)service.Any(balanceRequest)).Result.Where(Ar => Ar.Date == request.Date && (Ar.EntityId == request.EntityId || request.EntityId == null));
            });

     // filter cached response
     var filteredResponse = base.Cache.Get<GetBalanceResponse>("urn:balances").
                    Result.Where(Ar => Ar.Date == request.Date && (Ar.EntityId == request.EntityId || request.EntityId == null));

      return filteredResponse;
   }