【发布时间】:2018-08-20 20:33:57
【问题描述】:
我已被添加到一个正在开发的项目中。这是一个使用 Mediatr 和 CQRS 模式的 ASP.Net MVC 5 应用程序(具有只读数据库和只写数据库 - 最终一致)。该应用程序有一个管理部分,其中包含大量 CRUD 操作,我们遇到了问题。例如,假设有一个 Widget Controller:
public class WidgetController : Controller
{
private readonly IMediator _mediator;
public WidgetController(IMediator mediator)
{
_mediator = mediator;
}
// GET: Widget
public ActionResult Index()
{
// Reads from the read-only database and may not have synced
// This call is not guaranteed to have the newly added or edited widget (and usually doesn't)
var allWidgets = _mediator.Send(new GetAllWidgets());
return View(allWidgets);
}
[HttpPost]
public ActionResult Create(Widget widget)
{
try
{
// This call contains the database logic to write into the write only database
_mediator.Send(new CreateWidget(widget));
return RedirectToAction("Index");
}
catch
{
return View();
}
}
[HttpPost]
public ActionResult Edit(Widget updatedWidget)
{
try
{
// Writes to the write-only database
_mediator.Send(new UpdateWidget(updatedWidget));
return RedirectToAction("Index");
}
catch
{
return View();
}
}
}
在“创建”和“编辑”操作中,创建或编辑小部件,并且对只写数据库进行这些更改。随后立即重定向到从只读数据库读取的索引操作。在此调用完成并呈现视图时,这些更改通常不会从只写数据库同步。为了解决这个问题,我们使用 Redis 来缓存新创建或更新的对象,然后如果在 Index 操作中检索到的列表不包含新的或编辑的对象,我们会从缓存中检索它。 这感觉非常非常错误。
由于我们项目中的任何人都没有参与过 CQRS 项目,因此我们不知道如何解决这个问题。感觉我们真的错过了这种模式的一些东西。
所以,我想我要问的是......是否有处理这种情况的最佳实践?有没有更好的方法来做到这一点?
【问题讨论】: