Mediatr - 使缓存失效/更新的正确位置在哪里

Zoi*_*nky 6 c# caching cqrs microservices mediatr

这个问题源于我问过的关于太多接口、QCRS 和 Mediatr 库(请求/响应)的另一个问题

Mediatr:减少 DI 对象的数量

我创建了一堆命令和查询,我有一堆行为,其中一个是缓存行为,对于每个查询,在实际针对数据库执行查询之前,会检查缓存的值。到目前为止,这很好用,但是当我有一个 UpdateSomethingCommand 时,delima 就出现了,一旦我更新了数据库中的底层对象,我想用成功保存到数据库的内容刷新缓存。

我的问题是具体何时实际更新缓存:

  1. 在 UpdateSomethingCommandHandler 中(这可能会破坏 SOLID 主体)
  2. 在 UpdateSomethingCommandHanlder 中调用另一个专门用于更新缓存的命令(不确定这是一个好的设计原则)
  3. 引入另一种专为更新缓存而设计的行为(尚不确定如何进行)
  4. 有更好的解决方案吗?

djj*_*wis 6

我们对一个使用 MediatR 的项目有类似的需求,最终将缓存合并到中介管道中,包括您描述的缓存失效。

基本前提是我们在管道中插入了两种不同的行为,一种用于缓存来自请求的响应,另一种用于使来自不同请求的缓存请求响应无效。

这两种行为之间存在一些相互作用,因为它们需要交换缓存密钥以使正确的请求无效。

我最近将其中的一些工作放到了一个独立的库中,理论上可以按原样将其放入任何使用 MediatR 的项目中。在您的情况下,您可能只想查看我们在此处使用的技术并根据需要重新创建它们。

Rather than repeat everything here and now, I'll point you at the project page where there is some documentation under the Getting Started link on the homepage: https://github.com/Imprise/Imprise.MediatR.Extensions.Caching

In my opinion, the cache invalidation makes the whole process extremely simple and straightforward, but there are cases where we needed finer control over when the invalidation occurs. In these cases the other approach we have taken is to inject an ICache<TRequest, TResponse> cache into INotificationHandlers and then call _cache.Remove(key); manually as needed. Then, from any requests you know should invalidate just raise a notification that is handled by the INotificationHandler e.g. _mediator.Publish(SomethingUpdated);