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 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449
|
@Service public class MongoCrossDatabaseQueryService {
@Autowired private MongoTemplate userMongoTemplate;
@Autowired private MongoTemplate orderMongoTemplate;
@Autowired private MongoTemplate productMongoTemplate;
@Autowired private MongoTemplate paymentMongoTemplate;
@Autowired private RedisTemplate<String, Object> redisTemplate;
private final String CROSS_DB_CACHE_PREFIX = "cross_db_cache:"; private final long CROSS_DB_CACHE_EXPIRE = 1800;
public UserCompleteInfo crossDatabaseQueryUserCompleteInfo(Long userId) { try { String cacheKey = CROSS_DB_CACHE_PREFIX + "user_complete:" + userId; UserCompleteInfo cachedInfo = (UserCompleteInfo) redisTemplate.opsForValue().get(cacheKey);
if (cachedInfo != null) { return cachedInfo; }
CompletableFuture<UserInfo> userFuture = CompletableFuture.supplyAsync(() -> { return getUserInfoFromUserDB(userId); });
CompletableFuture<List<OrderInfo>> ordersFuture = CompletableFuture.supplyAsync(() -> { return getOrdersFromOrderDB(userId); });
CompletableFuture<List<ProductInfo>> productsFuture = CompletableFuture.supplyAsync(() -> { return getProductsFromProductDB(userId); });
CompletableFuture<List<PaymentInfo>> paymentsFuture = CompletableFuture.supplyAsync(() -> { return getPaymentsFromPaymentDB(userId); });
CompletableFuture<Void> allFutures = CompletableFuture.allOf( userFuture, ordersFuture, productsFuture, paymentsFuture);
allFutures.get();
UserCompleteInfo userCompleteInfo = new UserCompleteInfo(); userCompleteInfo.setUserId(userId); userCompleteInfo.setUserInfo(userFuture.get()); userCompleteInfo.setOrders(ordersFuture.get()); userCompleteInfo.setProducts(productsFuture.get()); userCompleteInfo.setPayments(paymentsFuture.get());
calculateUserCompleteStatistics(userCompleteInfo);
redisTemplate.opsForValue().set(cacheKey, userCompleteInfo, Duration.ofSeconds(CROSS_DB_CACHE_EXPIRE));
return userCompleteInfo;
} catch (Exception e) { log.error("跨库查询用户完整信息失败", e); throw new MongoCrossDatabaseQueryException("跨库查询用户完整信息失败", e); } }
private UserInfo getUserInfoFromUserDB(Long userId) { try { Query query = new Query(Criteria.where("_id").is(userId)); return userMongoTemplate.findOne(query, UserInfo.class, "users"); } catch (Exception e) { log.error("从用户数据库获取用户信息失败", e); throw new MongoCrossDatabaseQueryException("从用户数据库获取用户信息失败", e); } }
private List<OrderInfo> getOrdersFromOrderDB(Long userId) { try { Query query = new Query(Criteria.where("userId").is(userId)); query.with(Sort.by(Sort.Direction.DESC, "createTime")); return orderMongoTemplate.find(query, OrderInfo.class, "orders"); } catch (Exception e) { log.error("从订单数据库获取订单信息失败", e); throw new MongoCrossDatabaseQueryException("从订单数据库获取订单信息失败", e); } }
private List<ProductInfo> getProductsFromProductDB(Long userId) { try { Query orderQuery = new Query(Criteria.where("userId").is(userId)); orderQuery.fields().include("productId"); List<OrderInfo> orders = orderMongoTemplate.find(orderQuery, OrderInfo.class, "orders");
if (orders.isEmpty()) { return new ArrayList<>(); }
List<Long> productIds = orders.stream() .map(OrderInfo::getProductId) .distinct() .collect(Collectors.toList());
Query productQuery = new Query(Criteria.where("_id").in(productIds)); return productMongoTemplate.find(productQuery, ProductInfo.class, "products");
} catch (Exception e) { log.error("从商品数据库获取商品信息失败", e); throw new MongoCrossDatabaseQueryException("从商品数据库获取商品信息失败", e); } }
private List<PaymentInfo> getPaymentsFromPaymentDB(Long userId) { try { Query query = new Query(Criteria.where("userId").is(userId)); query.with(Sort.by(Sort.Direction.DESC, "createTime")); return paymentMongoTemplate.find(query, PaymentInfo.class, "payments"); } catch (Exception e) { log.error("从支付数据库获取支付信息失败", e); throw new MongoCrossDatabaseQueryException("从支付数据库获取支付信息失败", e); } }
private void calculateUserCompleteStatistics(UserCompleteInfo userCompleteInfo) { try { UserCompleteStatistics statistics = new UserCompleteStatistics();
List<OrderInfo> orders = userCompleteInfo.getOrders(); if (orders != null && !orders.isEmpty()) { statistics.setTotalOrders(orders.size()); statistics.setTotalOrderAmount(orders.stream() .mapToDouble(OrderInfo::getAmount) .sum());
Map<String, Long> statusCount = orders.stream() .collect(Collectors.groupingBy(OrderInfo::getStatus, Collectors.counting())); statistics.setOrderStatusCount(statusCount);
Map<String, Long> timeCount = orders.stream() .collect(Collectors.groupingBy(order -> order.getCreateTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate().toString(), Collectors.counting())); statistics.setOrderTimeCount(timeCount); }
List<ProductInfo> products = userCompleteInfo.getProducts(); if (products != null && !products.isEmpty()) { statistics.setTotalProducts(products.size()); statistics.setTotalProductAmount(products.stream() .mapToDouble(ProductInfo::getPrice) .sum());
Map<String, Long> categoryCount = products.stream() .collect(Collectors.groupingBy(ProductInfo::getCategory, Collectors.counting())); statistics.setProductCategoryCount(categoryCount); }
List<PaymentInfo> payments = userCompleteInfo.getPayments(); if (payments != null && !payments.isEmpty()) { statistics.setTotalPayments(payments.size()); statistics.setTotalPaymentAmount(payments.stream() .mapToDouble(PaymentInfo::getAmount) .sum());
Map<String, Long> paymentMethodCount = payments.stream() .collect(Collectors.groupingBy(PaymentInfo::getPaymentMethod, Collectors.counting())); statistics.setPaymentMethodCount(paymentMethodCount); }
userCompleteInfo.setStatistics(statistics);
} catch (Exception e) { log.error("计算用户完整统计信息失败", e); } }
public OrderDetailInfo crossDatabaseQueryOrderDetailInfo(Long orderId) { try { String cacheKey = CROSS_DB_CACHE_PREFIX + "order_detail:" + orderId; OrderDetailInfo cachedInfo = (OrderDetailInfo) redisTemplate.opsForValue().get(cacheKey);
if (cachedInfo != null) { return cachedInfo; }
CompletableFuture<OrderInfo> orderFuture = CompletableFuture.supplyAsync(() -> { return getOrderInfoFromOrderDB(orderId); });
CompletableFuture<List<ProductInfo>> productsFuture = CompletableFuture.supplyAsync(() -> { OrderInfo order = orderFuture.join(); return getProductsByOrderIdFromProductDB(order.getProductId()); });
CompletableFuture<UserInfo> userFuture = CompletableFuture.supplyAsync(() -> { OrderInfo order = orderFuture.join(); return getUserInfoFromUserDB(order.getUserId()); });
CompletableFuture<List<PaymentInfo>> paymentsFuture = CompletableFuture.supplyAsync(() -> { OrderInfo order = orderFuture.join(); return getPaymentsByOrderIdFromPaymentDB(orderId); });
CompletableFuture<Void> allFutures = CompletableFuture.allOf( orderFuture, productsFuture, userFuture, paymentsFuture); allFutures.get();
OrderDetailInfo orderDetailInfo = new OrderDetailInfo(); orderDetailInfo.setOrderInfo(orderFuture.get()); orderDetailInfo.setProducts(productsFuture.get()); orderDetailInfo.setUserInfo(userFuture.get()); orderDetailInfo.setPayments(paymentsFuture.get());
redisTemplate.opsForValue().set(cacheKey, orderDetailInfo, Duration.ofSeconds(CROSS_DB_CACHE_EXPIRE));
return orderDetailInfo;
} catch (Exception e) { log.error("跨库查询订单详细信息失败", e); throw new MongoCrossDatabaseQueryException("跨库查询订单详细信息失败", e); } }
private OrderInfo getOrderInfoFromOrderDB(Long orderId) { try { Query query = new Query(Criteria.where("_id").is(orderId)); return orderMongoTemplate.findOne(query, OrderInfo.class, "orders"); } catch (Exception e) { log.error("从订单数据库获取订单信息失败", e); throw new MongoCrossDatabaseQueryException("从订单数据库获取订单信息失败", e); } }
private List<ProductInfo> getProductsByOrderIdFromProductDB(Long productId) { try { Query query = new Query(Criteria.where("_id").is(productId)); return productMongoTemplate.find(query, ProductInfo.class, "products"); } catch (Exception e) { log.error("根据订单ID从商品数据库获取商品信息失败", e); throw new MongoCrossDatabaseQueryException("根据订单ID从商品数据库获取商品信息失败", e); } }
private List<PaymentInfo> getPaymentsByOrderIdFromPaymentDB(Long orderId) { try { Query query = new Query(Criteria.where("orderId").is(orderId)); return paymentMongoTemplate.find(query, PaymentInfo.class, "payments"); } catch (Exception e) { log.error("根据订单ID从支付数据库获取支付信息失败", e); throw new MongoCrossDatabaseQueryException("根据订单ID从支付数据库获取支付信息失败", e); } }
public ProductSalesStatistics crossDatabaseQueryProductSalesStatistics(Long productId, Date startTime, Date endTime) { try { String cacheKey = CROSS_DB_CACHE_PREFIX + "product_sales:" + productId + ":" + startTime.getTime() + ":" + endTime.getTime(); ProductSalesStatistics cachedStats = (ProductSalesStatistics) redisTemplate.opsForValue().get(cacheKey);
if (cachedStats != null) { return cachedStats; }
CompletableFuture<ProductInfo> productFuture = CompletableFuture.supplyAsync(() -> { return getProductInfoFromProductDB(productId); });
CompletableFuture<List<OrderInfo>> ordersFuture = CompletableFuture.supplyAsync(() -> { return getOrdersByProductIdFromOrderDB(productId, startTime, endTime); });
CompletableFuture<List<PaymentInfo>> paymentsFuture = CompletableFuture.supplyAsync(() -> { return getPaymentsByProductIdFromPaymentDB(productId, startTime, endTime); });
CompletableFuture<Void> allFutures = CompletableFuture.allOf( productFuture, ordersFuture, paymentsFuture); allFutures.get();
ProductSalesStatistics statistics = new ProductSalesStatistics(); statistics.setProductInfo(productFuture.get()); statistics.setTotalOrders(ordersFuture.get().size()); statistics.setTotalSales(ordersFuture.get().stream() .mapToDouble(OrderInfo::getAmount) .sum()); statistics.setTotalPayments(paymentsFuture.get().size()); statistics.setTotalPaymentAmount(paymentsFuture.get().stream() .mapToDouble(PaymentInfo::getAmount) .sum());
calculateSalesTrend(statistics, ordersFuture.get());
redisTemplate.opsForValue().set(cacheKey, statistics, Duration.ofSeconds(CROSS_DB_CACHE_EXPIRE));
return statistics;
} catch (Exception e) { log.error("跨库查询商品销售统计失败", e); throw new MongoCrossDatabaseQueryException("跨库查询商品销售统计失败", e); } }
private ProductInfo getProductInfoFromProductDB(Long productId) { try { Query query = new Query(Criteria.where("_id").is(productId)); return productMongoTemplate.findOne(query, ProductInfo.class, "products"); } catch (Exception e) { log.error("从商品数据库获取商品信息失败", e); throw new MongoCrossDatabaseQueryException("从商品数据库获取商品信息失败", e); } }
private List<OrderInfo> getOrdersByProductIdFromOrderDB(Long productId, Date startTime, Date endTime) { try { Query query = new Query(Criteria.where("productId").is(productId) .and("createTime").gte(startTime).lte(endTime)); return orderMongoTemplate.find(query, OrderInfo.class, "orders"); } catch (Exception e) { log.error("根据商品ID从订单数据库获取订单信息失败", e); throw new MongoCrossDatabaseQueryException("根据商品ID从订单数据库获取订单信息失败", e); } }
private List<PaymentInfo> getPaymentsByProductIdFromPaymentDB(Long productId, Date startTime, Date endTime) { try { Query query = new Query(Criteria.where("productId").is(productId) .and("createTime").gte(startTime).lte(endTime)); return paymentMongoTemplate.find(query, PaymentInfo.class, "payments"); } catch (Exception e) { log.error("根据商品ID从支付数据库获取支付信息失败", e); throw new MongoCrossDatabaseQueryException("根据商品ID从支付数据库获取支付信息失败", e); } }
private void calculateSalesTrend(ProductSalesStatistics statistics, List<OrderInfo> orders) { try { Map<String, Double> dailySales = orders.stream() .collect(Collectors.groupingBy(order -> order.getCreateTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate().toString(), Collectors.summingDouble(OrderInfo::getAmount)));
statistics.setDailySalesTrend(dailySales);
Map<String, Double> weeklySales = orders.stream() .collect(Collectors.groupingBy(order -> { LocalDate date = order.getCreateTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate(); return date.getYear() + "-W" + date.get(WeekFields.ISO.weekOfYear()); }, Collectors.summingDouble(OrderInfo::getAmount)));
statistics.setWeeklySalesTrend(weeklySales);
Map<String, Double> monthlySales = orders.stream() .collect(Collectors.groupingBy(order -> { LocalDate date = order.getCreateTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate(); return date.getYear() + "-" + String.format("%02d", date.getMonthValue()); }, Collectors.summingDouble(OrderInfo::getAmount)));
statistics.setMonthlySalesTrend(monthlySales);
} catch (Exception e) { log.error("计算销售趋势失败", e); } } }
|