【问题标题】:How to cache IQueryable result for paging如何缓存 IQueryable 结果以进行分页
【发布时间】:2015-08-01 15:06:04
【问题描述】:

如果每次调用都需要计算很多东西并将其返回给客户端,那么缓存 Queryable 结果的最佳方法是什么。

代码示例

 [Queryable]
 public IQueryable<Car> Get()
 {
    try
    {
    var result=GetCarList();
    //GetCarList() calculation is  taking  around 1 min

    return result.AsQueryable();
    } 
 }

GetCarList()
{
var query = from car in db.CarDetail
            where car.color == "white"
            select car;

//10k records of white cars are selected with out considering makers 
//white is mandatory
foreach (var car in query)
{
  //Processing each record in every call
}
}

查询示例

首页

localhost/api/Car?$filter=(make eq 'ford')&$orderby=carid desc&$top=10

第二页

localhost/api/Car?$filter=(make eq 'ford')&$orderby=carid desc&$top=10$skip=10

第三页

localhost/api/Car?$filter=(make eq 'ford')&$orderby=carid desc&$top=10$skip=20

每次调用都需要 1 分钟,即使当前过滤器的计算相同。缓存这种 api 调用的最佳方法是什么?

【问题讨论】:

标签: caching asp.net-web-api odata asp.net-web-api2


【解决方案1】:

正如 OP 在他的评论中解释的那样,要缓存的对象是调用 GetCarList(); 返回的列表,结果始终相同。

您可以简单地将其存储在缓存中,请参阅文档:Cache Class

当你需要它时,检查它是否在缓存中。如果没有,请在使用前创建它并存储在缓存中(在您想使用它的任何地方)。由于Cache 是线程安全的,因此通过从不同的请求访问它,您不会遇到并发问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-24
    • 1970-01-01
    • 2013-12-05
    • 2020-06-23
    • 1970-01-01
    • 2010-09-11
    • 2021-05-22
    相关资源
    最近更新 更多