代码之家  ›  专栏  ›  技术社区  ›  Collin Barrett

抽象对API中IMemorycache的异步调用

  •  4
  • Collin Barrett  · 技术社区  · 6 年前

    我一直在使用类似于示例1的操作来为我的.NET核心API异步缓存JSON结果。 MemoryCache 是的实例 IMemoryCache .

    例1(按预期工作):

    [HttpGet]
    public async Task<IActionResult> MyAction() =>
        Json(await MemoryCache.GetOrCreateAsync(
            "MyController_MyAction", 
            entry => myService.GetAllAsync()
        ));
    

    呼唤 Json() MemoryCache.GetOrCreate() 在我的许多行为中都是重复的。在我的真实应用程序中,有更多重复的实现细节,例如设置 AbsoluteExpirationRelativeToNow 价值与回报 NotFound() 对于空值。我想将所有这些抽象到一个共享方法中,以便每个操作只将其唯一的细节传递给共享方法的调用。

    为了做到这一点,我为我的操作中的两个变量中的每一个提取了一个变量。例如。:

    示例2(缓存既不更新也不从中检索):

    [HttpGet]
    public async Task<IActionResult> MyAction()
    {
        var task = myService.GetAllAsync();
        const string cacheKey = "MyController_MyAction";
        return Json(await MemoryCache.GetOrCreateAsync(cacheKey, entry => task));
    }
    

    下一步是提取共享方法 Get() 像:

    示例3(不起作用,因为示例2不起作用):

    [HttpGet]
    public async Task<IActionResult> MyAction()
    {
        var task = myService.GetAllAsync();
        const string cacheKey = "MyController_MyAction";
        return await Get(task, cacheKey);
    }
    
    protected async Task<IActionResult> Get(Task<T> task, string cacheKey =>
        return Json(await MemoryCache.GetOrCreateAsync(cacheKey, entry => task));
    

    示例1成功地从缓存中检索后续结果。然而,示例2发现 null 在后续请求的缓存中,并每次重新检索数据(由临时调试验证) TryGetValue() 语句,以及监视命中我的数据库的底层SQL查询)。

    对我来说,示例1和示例2应该是相同的。但是,可能我对异步/等待和任务的理解是缺乏的(很可能)。

    我如何抽象出重复的实现细节(例如 JSON() memorycache.getorCreate()。 调用)从我的操作,同时仍成功更新和检索 IimeRyCuffice 以异步方式?

    2 回复  |  直到 6 年前
        1
  •  4
  •   poke    6 年前
    var task = myService.GetAllAsync();
    

    这将运行 GetAllAsync 方法,因此通过这样做,可以防止内存缓存的懒惰行为,因为只有当缓存键不可用时,它才会调用该方法。

    为了继续这样做,必须存储创建值的实际表达式,因此必须执行以下操作:

    Func<MyObject> createValue = () => myService.GetAllAsync();
    const string cacheKey = "MyController_MyAction";
    return Json(await MemoryCache.GetOrCreateAsync(cacheKey, entry => createValue()));
    

    所以,把它抽象化,这就是你最终可以得到的:

    public Task<IActionResult> MyAction()
        => GetCache("MyController_MyAction", () => myService.GetAllAsync());
    

    该方法的实现方式如下:

    private async Task<IActionResult> GetCache<T>(string cacheKey, Func<Task<T>> createAction)
    {
        var result = await MemoryCache.GetOrCreateAsync(cacheKey, entry => createAction());
        return Json(result);
    }
    

    如果缓存键总是 <ControllerName>_<ActionName> ,您甚至可以再执行一步,并使用 CallerMemberNameAttribute :

    private async Task<IActionResult> GetCache<T>(Func<Task<T>> createAction, [CallerMemberName] string actionName = null)
    {
        var cacheKey = GetType().Name + "_" + actionName;
        var result = await MemoryCache.GetOrCreateAsync(cacheKey, entry => createAction());
        return Json(result);
    }
    

    所以你可以这样使用它:

    public Task<IActionResult> MyAction()
        => GetCache(() => myService.GetAllAsync());
    
        2
  •  1
  •   Travis J    6 年前

    var task = myService.GetAllAsync(); 不会创建您需要的func签名。

    public static System.Threading.Tasks.Task<TItem> GetOrCreateAsync<TItem> ( this Microsoft.Extensions.Caching.Memory.IMemoryCache cache, object key, Func<Microsoft.Extensions.Caching.Memory.ICacheEntry, System.Threading.Tasks.Task<TItem>> factory );
    - CacheExtensions.GetOrCreateAsync MSDN

    相反,创建func

    Func<ICacheEntry,Task<TItem>> taskFunc = entry => myService.GetAllAsync();
    

    然后根据需要重新使用

    return Json(await MemoryCache.GetOrCreateAsync(cacheKey, taskFunc));