1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421
|
@Service public class RedisAggregationQueryService {
@Autowired private RedisTemplate<String, Object> userRedisTemplate;
@Autowired private RedisTemplate<String, Object> orderRedisTemplate;
@Autowired private RedisTemplate<String, Object> productRedisTemplate;
@Autowired private RedisTemplate<String, Object> paymentRedisTemplate;
@Autowired private RedisTemplate<String, Object> cacheRedisTemplate;
private final String REDIS_AGGREGATION_CACHE_PREFIX = "redis_aggregation_cache:"; private final long REDIS_AGGREGATION_CACHE_EXPIRE = 1800;
public UserOrderAggregationResult aggregateUserOrderStatistics(Long userId) { try { String cacheKey = REDIS_AGGREGATION_CACHE_PREFIX + "user_order_stats:" + userId; UserOrderAggregationResult cachedResult = (UserOrderAggregationResult) cacheRedisTemplate.opsForValue().get(cacheKey);
if (cachedResult != null) { return cachedResult; }
OrderStatistics orderStats = queryOrderStatistics(userId);
ProductStatistics productStats = queryProductStatistics(userId);
PaymentStatistics paymentStats = queryPaymentStatistics(userId);
UserOrderAggregationResult result = aggregateStatistics(userId, orderStats, productStats, paymentStats);
cacheRedisTemplate.opsForValue().set(cacheKey, result, Duration.ofSeconds(REDIS_AGGREGATION_CACHE_EXPIRE));
return result;
} catch (Exception e) { log.error("聚合查询用户订单统计失败", e); throw new RedisCrossDatabaseQueryException("聚合查询用户订单统计失败", e); } }
private OrderStatistics queryOrderStatistics(Long userId) { try { String orderKey = "user_orders:" + userId; Long totalOrders = userRedisTemplate.opsForSet().size(orderKey);
String orderDetailKey = "user_orders:" + userId; Set<Object> orderIds = userRedisTemplate.opsForSet().members(orderDetailKey);
double totalAmount = 0.0; double minAmount = Double.MAX_VALUE; double maxAmount = Double.MIN_VALUE; Map<String, Long> statusCount = new HashMap<>();
if (orderIds != null && !orderIds.isEmpty()) { for (Object orderId : orderIds) { String orderKeyDetail = "order:" + orderId; OrderInfo orderInfo = (OrderInfo) orderRedisTemplate.opsForValue().get(orderKeyDetail); if (orderInfo != null) { double amount = orderInfo.getAmount(); totalAmount += amount; minAmount = Math.min(minAmount, amount); maxAmount = Math.max(maxAmount, amount);
String status = orderInfo.getStatus(); statusCount.put(status, statusCount.getOrDefault(status, 0L) + 1); } } }
double avgAmount = totalOrders > 0 ? totalAmount / totalOrders : 0.0;
OrderStatistics orderStats = new OrderStatistics(); orderStats.setUserId(userId); orderStats.setTotalOrders(totalOrders); orderStats.setTotalAmount(totalAmount); orderStats.setAvgAmount(avgAmount); orderStats.setMinAmount(minAmount == Double.MAX_VALUE ? 0.0 : minAmount); orderStats.setMaxAmount(maxAmount == Double.MIN_VALUE ? 0.0 : maxAmount); orderStats.setStatusCount(statusCount);
return orderStats;
} catch (Exception e) { log.error("查询订单统计失败", e); throw new RedisCrossDatabaseQueryException("查询订单统计失败", e); } }
private ProductStatistics queryProductStatistics(Long userId) { try { String productKey = "user_products:" + userId; Long totalProducts = userRedisTemplate.opsForSet().size(productKey);
String productDetailKey = "user_products:" + userId; Set<Object> productIds = userRedisTemplate.opsForSet().members(productDetailKey);
double totalPrice = 0.0; double minPrice = Double.MAX_VALUE; double maxPrice = Double.MIN_VALUE; Map<String, Long> categoryCount = new HashMap<>();
if (productIds != null && !productIds.isEmpty()) { for (Object productId : productIds) { String productKeyDetail = "product:" + productId; ProductInfo productInfo = (ProductInfo) productRedisTemplate.opsForValue().get(productKeyDetail); if (productInfo != null) { double price = productInfo.getPrice(); totalPrice += price; minPrice = Math.min(minPrice, price); maxPrice = Math.max(maxPrice, price);
String category = productInfo.getCategory(); categoryCount.put(category, categoryCount.getOrDefault(category, 0L) + 1); } } }
double avgPrice = totalProducts > 0 ? totalPrice / totalProducts : 0.0;
ProductStatistics productStats = new ProductStatistics(); productStats.setUserId(userId); productStats.setTotalProducts(totalProducts); productStats.setTotalPrice(totalPrice); productStats.setAvgPrice(avgPrice); productStats.setMinPrice(minPrice == Double.MAX_VALUE ? 0.0 : minPrice); productStats.setMaxPrice(maxPrice == Double.MIN_VALUE ? 0.0 : maxPrice); productStats.setCategoryCount(categoryCount);
return productStats;
} catch (Exception e) { log.error("查询商品统计失败", e); throw new RedisCrossDatabaseQueryException("查询商品统计失败", e); } }
private PaymentStatistics queryPaymentStatistics(Long userId) { try { String paymentKey = "user_payments:" + userId; Long totalPayments = userRedisTemplate.opsForSet().size(paymentKey);
String paymentDetailKey = "user_payments:" + userId; Set<Object> paymentIds = userRedisTemplate.opsForSet().members(paymentDetailKey);
double totalAmount = 0.0; double minAmount = Double.MAX_VALUE; double maxAmount = Double.MIN_VALUE; Map<String, Long> methodCount = new HashMap<>();
if (paymentIds != null && !paymentIds.isEmpty()) { for (Object paymentId : paymentIds) { String paymentKeyDetail = "payment:" + paymentId; PaymentInfo paymentInfo = (PaymentInfo) paymentRedisTemplate.opsForValue().get(paymentKeyDetail); if (paymentInfo != null) { double amount = paymentInfo.getAmount(); totalAmount += amount; minAmount = Math.min(minAmount, amount); maxAmount = Math.max(maxAmount, amount);
String paymentMethod = paymentInfo.getPaymentMethod(); methodCount.put(paymentMethod, methodCount.getOrDefault(paymentMethod, 0L) + 1); } } }
double avgAmount = totalPayments > 0 ? totalAmount / totalPayments : 0.0;
PaymentStatistics paymentStats = new PaymentStatistics(); paymentStats.setUserId(userId); paymentStats.setTotalPayments(totalPayments); paymentStats.setTotalAmount(totalAmount); paymentStats.setAvgAmount(avgAmount); paymentStats.setMinAmount(minAmount == Double.MAX_VALUE ? 0.0 : minAmount); paymentStats.setMaxAmount(maxAmount == Double.MIN_VALUE ? 0.0 : maxAmount); paymentStats.setMethodCount(methodCount);
return paymentStats;
} catch (Exception e) { log.error("查询支付统计失败", e); throw new RedisCrossDatabaseQueryException("查询支付统计失败", e); } }
private UserOrderAggregationResult aggregateStatistics(Long userId, OrderStatistics orderStats, ProductStatistics productStats, PaymentStatistics paymentStats) { try { UserOrderAggregationResult result = new UserOrderAggregationResult(); result.setUserId(userId);
result.setTotalOrders(orderStats.getTotalOrders()); result.setTotalOrderAmount(orderStats.getTotalAmount()); result.setAvgOrderAmount(orderStats.getAvgAmount()); result.setOrderStatusCount(orderStats.getStatusCount());
result.setTotalProducts(productStats.getTotalProducts()); result.setTotalProductAmount(productStats.getTotalPrice()); result.setAvgProductPrice(productStats.getAvgPrice()); result.setProductCategoryCount(productStats.getCategoryCount());
result.setTotalPayments(paymentStats.getTotalPayments()); result.setTotalPaymentAmount(paymentStats.getTotalAmount()); result.setAvgPaymentAmount(paymentStats.getAvgAmount()); result.setPaymentMethodCount(paymentStats.getMethodCount());
calculateComprehensiveStatistics(result);
return result;
} catch (Exception e) { log.error("聚合统计信息失败", e); throw new RedisCrossDatabaseQueryException("聚合统计信息失败", e); } }
private void calculateComprehensiveStatistics(UserOrderAggregationResult result) { try { ComprehensiveStatistics comprehensiveStats = new ComprehensiveStatistics();
comprehensiveStats.setTotalAmount(result.getTotalOrderAmount() + result.getTotalProductAmount());
comprehensiveStats.setTotalCount(result.getTotalOrders() + result.getTotalProducts() + result.getTotalPayments());
comprehensiveStats.setAvgAmount(comprehensiveStats.getTotalCount() > 0 ? comprehensiveStats.getTotalAmount() / comprehensiveStats.getTotalCount() : 0.0);
result.setComprehensiveStatistics(comprehensiveStats);
} catch (Exception e) { log.error("计算综合统计失败", e); } }
public ComplexAggregationResult executeComplexAggregation(ComplexAggregationRequest request) { try { ComplexAggregationResult result = new ComplexAggregationResult(); result.setRequestId(request.getRequestId()); result.setStartTime(new Date());
List<Map<String, Object>> aggregationResults = new ArrayList<>();
for (AggregationQuery query : request.getQueries()) { try { List<Map<String, Object>> queryResults = executeAggregationQuery(query); aggregationResults.addAll(queryResults); } catch (Exception e) { log.error("执行聚合查询失败: {}", query.getQueryType(), e); } }
result.setAggregationResults(aggregationResults); result.setTotalCount(aggregationResults.size()); result.setEndTime(new Date()); result.setStatus(AggregationStatus.SUCCESS);
return result;
} catch (Exception e) { log.error("执行复杂聚合查询失败", e); throw new RedisCrossDatabaseQueryException("执行复杂聚合查询失败", e); } }
private List<Map<String, Object>> executeAggregationQuery(AggregationQuery query) { try { List<Map<String, Object>> results = new ArrayList<>();
switch (query.getQueryType()) { case ORDER_STATISTICS: results = executeOrderStatisticsQuery(query); break; case PRODUCT_STATISTICS: results = executeProductStatisticsQuery(query); break; case PAYMENT_STATISTICS: results = executePaymentStatisticsQuery(query); break; default: log.warn("不支持的聚合查询类型: {}", query.getQueryType()); break; }
return results;
} catch (Exception e) { log.error("执行聚合查询失败", e); throw new RedisCrossDatabaseQueryException("执行聚合查询失败", e); } }
private List<Map<String, Object>> executeOrderStatisticsQuery(AggregationQuery query) { try { List<Map<String, Object>> results = new ArrayList<>();
Map<String, Object> orderStats = new HashMap<>(); orderStats.put("totalOrders", 100); orderStats.put("totalAmount", 10000.0); orderStats.put("avgAmount", 100.0);
results.add(orderStats);
return results;
} catch (Exception e) { log.error("执行订单统计查询失败", e); throw new RedisCrossDatabaseQueryException("执行订单统计查询失败", e); } }
private List<Map<String, Object>> executeProductStatisticsQuery(AggregationQuery query) { try { List<Map<String, Object>> results = new ArrayList<>();
Map<String, Object> productStats = new HashMap<>(); productStats.put("totalProducts", 50); productStats.put("totalPrice", 5000.0); productStats.put("avgPrice", 100.0);
results.add(productStats);
return results;
} catch (Exception e) { log.error("执行商品统计查询失败", e); throw new RedisCrossDatabaseQueryException("执行商品统计查询失败", e); } }
private List<Map<String, Object>> executePaymentStatisticsQuery(AggregationQuery query) { try { List<Map<String, Object>> results = new ArrayList<>();
Map<String, Object> paymentStats = new HashMap<>(); paymentStats.put("totalPayments", 80); paymentStats.put("totalAmount", 8000.0); paymentStats.put("avgAmount", 100.0);
results.add(paymentStats);
return results;
} catch (Exception e) { log.error("执行支付统计查询失败", e); throw new RedisCrossDatabaseQueryException("执行支付统计查询失败", e); } } }
|