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
|
@Service public class CassandraAggregationQueryService {
@Autowired private CassandraTemplate cassandraTemplate;
@Autowired private RedisTemplate<String, Object> redisTemplate;
private final String CASSANDRA_AGGREGATION_CACHE_PREFIX = "cassandra_aggregation_cache:"; private final long CASSANDRA_AGGREGATION_CACHE_EXPIRE = 1800;
public UserOrderAggregationResult aggregateUserOrderStatistics(Long userId) { try { String cacheKey = CASSANDRA_AGGREGATION_CACHE_PREFIX + "user_order_stats:" + userId; UserOrderAggregationResult cachedResult = (UserOrderAggregationResult) redisTemplate.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);
redisTemplate.opsForValue().set(cacheKey, result, Duration.ofSeconds(CASSANDRA_AGGREGATION_CACHE_EXPIRE));
return result;
} catch (Exception e) { log.error("聚合查询用户订单统计失败", e); throw new CassandraCrossDatabaseQueryException("聚合查询用户订单统计失败", e); } }
private OrderStatistics queryOrderStatistics(Long userId) { try { String countCql = "SELECT COUNT(*) FROM orders.orders WHERE user_id = ?"; Long totalOrders = cassandraTemplate.selectOne(countCql, Long.class, userId);
String amountCql = "SELECT SUM(amount) as total_amount, AVG(amount) as avg_amount, " + "MIN(amount) as min_amount, MAX(amount) as max_amount FROM orders.orders WHERE user_id = ?"; Map<String, Object> amountStats = cassandraTemplate.selectOne(amountCql, Map.class, userId);
String statusCql = "SELECT status, COUNT(*) as count FROM orders.orders WHERE user_id = ? GROUP BY status"; List<Map<String, Object>> statusStats = cassandraTemplate.select(statusCql, Map.class, userId);
OrderStatistics orderStats = new OrderStatistics(); orderStats.setUserId(userId); orderStats.setTotalOrders(totalOrders); orderStats.setTotalAmount((Double) amountStats.get("total_amount")); orderStats.setAvgAmount((Double) amountStats.get("avg_amount")); orderStats.setMinAmount((Double) amountStats.get("min_amount")); orderStats.setMaxAmount((Double) amountStats.get("max_amount"));
Map<String, Long> statusCount = new HashMap<>(); for (Map<String, Object> statusStat : statusStats) { statusCount.put((String) statusStat.get("status"), (Long) statusStat.get("count")); } orderStats.setStatusCount(statusCount);
return orderStats;
} catch (Exception e) { log.error("查询订单统计失败", e); throw new CassandraCrossDatabaseQueryException("查询订单统计失败", e); } }
private ProductStatistics queryProductStatistics(Long userId) { try { String countCql = "SELECT COUNT(*) FROM products.products WHERE user_id = ?"; Long totalProducts = cassandraTemplate.selectOne(countCql, Long.class, userId);
String priceCql = "SELECT SUM(price) as total_price, AVG(price) as avg_price, " + "MIN(price) as min_price, MAX(price) as max_price FROM products.products WHERE user_id = ?"; Map<String, Object> priceStats = cassandraTemplate.selectOne(priceCql, Map.class, userId);
String categoryCql = "SELECT category, COUNT(*) as count FROM products.products WHERE user_id = ? GROUP BY category"; List<Map<String, Object>> categoryStats = cassandraTemplate.select(categoryCql, Map.class, userId);
ProductStatistics productStats = new ProductStatistics(); productStats.setUserId(userId); productStats.setTotalProducts(totalProducts); productStats.setTotalPrice((Double) priceStats.get("total_price")); productStats.setAvgPrice((Double) priceStats.get("avg_price")); productStats.setMinPrice((Double) priceStats.get("min_price")); productStats.setMaxPrice((Double) priceStats.get("max_price"));
Map<String, Long> categoryCount = new HashMap<>(); for (Map<String, Object> categoryStat : categoryStats) { categoryCount.put((String) categoryStat.get("category"), (Long) categoryStat.get("count")); } productStats.setCategoryCount(categoryCount);
return productStats;
} catch (Exception e) { log.error("查询商品统计失败", e); throw new CassandraCrossDatabaseQueryException("查询商品统计失败", e); } }
private PaymentStatistics queryPaymentStatistics(Long userId) { try { String countCql = "SELECT COUNT(*) FROM payments.payments WHERE user_id = ?"; Long totalPayments = cassandraTemplate.selectOne(countCql, Long.class, userId);
String amountCql = "SELECT SUM(amount) as total_amount, AVG(amount) as avg_amount, " + "MIN(amount) as min_amount, MAX(amount) as max_amount FROM payments.payments WHERE user_id = ?"; Map<String, Object> amountStats = cassandraTemplate.selectOne(amountCql, Map.class, userId);
String methodCql = "SELECT payment_method, COUNT(*) as count FROM payments.payments WHERE user_id = ? GROUP BY payment_method"; List<Map<String, Object>> methodStats = cassandraTemplate.select(methodCql, Map.class, userId);
PaymentStatistics paymentStats = new PaymentStatistics(); paymentStats.setUserId(userId); paymentStats.setTotalPayments(totalPayments); paymentStats.setTotalAmount((Double) amountStats.get("total_amount")); paymentStats.setAvgAmount((Double) amountStats.get("avg_amount")); paymentStats.setMinAmount((Double) amountStats.get("min_amount")); paymentStats.setMaxAmount((Double) amountStats.get("max_amount"));
Map<String, Long> methodCount = new HashMap<>(); for (Map<String, Object> methodStat : methodStats) { methodCount.put((String) methodStat.get("payment_method"), (Long) methodStat.get("count")); } paymentStats.setMethodCount(methodCount);
return paymentStats;
} catch (Exception e) { log.error("查询支付统计失败", e); throw new CassandraCrossDatabaseQueryException("查询支付统计失败", 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 CassandraCrossDatabaseQueryException("聚合统计信息失败", 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 = cassandraTemplate.select(query.getCql(), Map.class, query.getParameters()); aggregationResults.addAll(queryResults); } catch (Exception e) { log.error("执行聚合查询失败: {}", query.getCql(), 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 CassandraCrossDatabaseQueryException("执行复杂聚合查询失败", e); } } }
|