From 93dca561eac0a84edd61d2bde3984775308c3e30 Mon Sep 17 00:00:00 2001 From: hello Date: Wed, 20 Nov 2024 07:21:01 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AE=9E=E7=8E=B0=20query=20=E6=A8=A1=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../helloshop/ordering-service-cqrs-query.md | 63 +++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 notes/helloshop/ordering-service-cqrs-query.md diff --git a/notes/helloshop/ordering-service-cqrs-query.md b/notes/helloshop/ordering-service-cqrs-query.md new file mode 100644 index 0000000..95bd62b --- /dev/null +++ b/notes/helloshop/ordering-service-cqrs-query.md @@ -0,0 +1,63 @@ +# 实现 CQRS 中的 Query 模式 + +在 CQRS 模式的全程是 Command Query Responsibility Segregation,即命令查询职责分离。在 CQRS 模式中,命令和查询是分开实现的,命令负责写操作,查询负责读操作,这样可以更好地实现单一职责原则,同时也可以更好地实现性能优化。 + +https://learn.microsoft.com/zh-cn/azure/architecture/patterns/cqrs + +### 定义订单查询接口 + +```csharp +public interface IOrderQueries +{ + Task GetOrderAsync(int id); +} +``` + +### 实现订单查询接口 + +```csharp +public class OrderQueries : IOrderQueries +{ + private readonly OrderingContext _context; + + public OrderQueries(OrderingContext context) + { + _context = context; + dbContext.Database.SetConnectionString("db2_connection_string"); + } + + public async Task GetOrderAsync(int id) + { + // do something + } +} +``` + +### 注册订单查询接口 + +```csharp +services.AddScoped(); +``` + +### 使用订单查询接口 + +```csharp +public class OrderController : ControllerBase +{ + private readonly IOrderQueries _orderQueries; + + public OrderController(IOrderQueries orderQueries) + { + _orderQueries = orderQueries; + } + + [HttpGet("{id}")] + public async Task GetOrderAsync(int id) + { + var order = await _orderQueries.GetOrderAsync(id); + return Ok(order); + } +} +``` + +