资源项总数计算(单独查询与集合)

resource items total count calculation (separate query vs collection)

我正在努力寻找在返回资源集合时获取所有项目的最佳方法我正在考虑两种方法,只是想听听您对什么是最好的意见?

场景:

用户想要从我的 10000 车辆中检索 10 车辆的列表,其中包含一些游标,例如(限制、之前、之后、过滤器等...)

选项 1:

class VehiclesRepo()
{
    function getVehicles(){
        // get 10000 vehicles with one query; : returns collection
        // return 10000 vehicles and do filtration on transformation layer to keep total_count of vehicles 
    }
}

选项 2:

class VehiclesRepo()
{
    function getVehicles(){
        // get 10 vehicles with one query including filtration; : returns collection
        // return 10 vehicles, and do another query for total_count
    }
}

请考虑操作对内存的影响,cpu圆圈?我的系统也完全是 DDD,所以我尽量避免域泄漏

im trying to do that without having to access infrastructure layer from outside the domain

这实际上是你的问题。 DDD 聚合是围绕命令处理、事务一致性和业务不变性而不是查询需求设计的。

这就是近来 CQRS 如此流行的原因。我强烈建议您不要依赖域模型来满足查询需求。

这两个选项基本上都可以,但我认为如果您使用选项 1,那么对于 10'000 辆车辆来说,您已经存在性能问题。所以我会选择选项 2。

但是你的设计可能还有其他问题:

I'm trying to do that without having to access infrastructure layer from outside the domain.

此评论表明您具有以下层次:

 Application
      ⇣
   Domain
      ⇣
Infrastructure

如果您不使用某种 Dependency Inversion Priciple 实际上使基础设施依赖于领域层,那么您的设计就有问题。域应尽可能纯净。如果域依赖于基础设施,这意味着您不能独立于基础设施使用您的域模型。这很糟糕,因为基础设施是人造的,在您域的真实世界中不存在。

所以你在概念上应该做的是:

Application
   ⇣     ⇣
   ⇣    Infrastructure
   ⇣    ⇣
   Domain 

然后您的存储库实现变得自然并允许查询操作,例如:

  • 给我 ID 为 X 的车辆
  • 给我所有超过 Y 轮的车辆
  • 给我所有符合过滤器 Z
  • 的车辆

请注意,这些查询操作应该 return 实际业务对象,而不是 DTO 或数据库行等。

如果您想了解更多有关 DDD 的不同架构的优缺点,我建议您阅读 Vaughn Vernon 的实施 DDD 中的 "Architecture" 章。


关于@plaxl 的回答的注意事项:答案是特定于 CQRS 的,您在问题中只字未提。因此,在 CQRS 上下文之外,使用域模型进行查询操作非常好。