【发布时间】:2020-01-09 09:09:57
【问题描述】:
我有一个 API 控制器,场景是:
我需要使用第三方数据源(为了简单起见,假设第三方作为 dll 文件提供,并且 dll 包含 Student 模型和 StudentDataSource 包含很多检索学生的方法),并调用第三方数据源成本高,数据每 6 小时更新一次。
所以我需要以某种方式缓存输出,下面是我的 api 控制器的一些操作方法:
// api controller that contain action methods below
[HttpGet]
public JsonResult GetAllStudentRecords()
{
var dataSource = new StudentDataSource();
return Json(dataSource.GetAllStudents());
}
[HttpGet("{id}")]
public JsonResult GetStudent(int id)
{
var dataSource = new StudentDataSource();
return Json(dataSource.getStudent(id));
}
那我应该如何缓存结果,尤其是对于第二种操作方法,缓存每个学生的结果具有不同的 id 是愚蠢的
【问题讨论】:
-
缓存策略高度依赖于您的用例。几乎不可能提出适合所有系统的通用方法 - 如果您可以添加更多信息(您的 api 多久调用一次,底层数据源有多大,响应有多大,您所说的“昂贵的”,...)可能会提出一个方向。
-
您可以尝试使用(System.Runtime.Caching 或 System.Web.Caching)。
-
您可以使用
IMemoryCache来缓存结果 -
您可以在 Asp Core 中使用 InMemoryCache:infoworld.com/article/3230129/…
-
@germi 那么如何缓存第二种操作方法的输出?我无法缓存具有不同 ID 的输出?
标签: c# .net web-services asp.net-core asp.net-core-mvc