Browse Source

perf: 门店列表 2N 次 COUNT → 1 次批量查询

- fillShopStats 逐行 2 次 COUNT 改为 1 次 SELECT + 内存分组统计
- 10 行门店从 20 次 DB 降到 1 次

Co-Authored-By: Claude <noreply@anthropic.com>
skyline 1 ngày trước cách đây
mục cha
commit
5818a609bf

+ 24 - 6
haha-service/src/main/java/com/haha/service/impl/ShopServiceImpl.java

@@ -63,13 +63,31 @@ public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements Sh
         wrapper.orderByDesc(Shop::getCreateTime);
         
         IPage<Shop> shopPage = this.page(pageParam, wrapper);
-        
-        // 填充设备统计信息
-        for (Shop shop : shopPage.getRecords()) {
-            fillShopStats(shop);
-            fillShopLabels(shop);
+
+        // 批量填充设备统计信息(1 次查询替代 2N 次 COUNT)
+        List<Shop> records = shopPage.getRecords();
+        if (!records.isEmpty()) {
+            List<Long> shopIds = records.stream().map(Shop::getId).toList();
+            // 一次查所有关联设备,在内存中按 shopId 分组统计
+            List<Device> allDevices = deviceService.lambdaQuery()
+                    .in(Device::getShopId, shopIds)
+                    .select(Device::getShopId, Device::getStatus)
+                    .list();
+            Map<Long, Integer> deviceCountMap = new HashMap<>();
+            Map<Long, Integer> onlineCountMap = new HashMap<>();
+            for (Device d : allDevices) {
+                deviceCountMap.merge(d.getShopId(), 1, Integer::sum);
+                if (d.getStatus() != null && d.getStatus() == DeviceConstants.STATUS_ONLINE) {
+                    onlineCountMap.merge(d.getShopId(), 1, Integer::sum);
+                }
+            }
+            for (Shop shop : records) {
+                shop.setDeviceCount(deviceCountMap.getOrDefault(shop.getId(), 0));
+                shop.setOnlineCount(onlineCountMap.getOrDefault(shop.getId(), 0));
+                fillShopLabels(shop);
+            }
         }
-        
+
         return shopPage;
     }