wzj-boot/ruoyi-modules/ruoyi-order/README_定时任务.md
2025-08-04 14:42:21 +08:00

111 lines
3.4 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 商品交易量排行榜定时任务
## 功能说明
本功能实现了每天12点自动查询交易量最多的100个商品并存储到Redis中的定时任务。
## 实现内容
### 1. 数据库查询
-`OrderItemMapper` 中添加了 `selectTopTradingProducts` 方法
- 查询条件已完成订单status = 3且未删除订单delete_status = 0
- 按销售数量降序排列取前100个商品
- 统计信息包括商品ID、商品名称、图片、总销售数量、总销售金额、订单数量
### 2. 服务层实现
-`OrderItemService` 接口中添加了 `cacheTopTradingProducts` 方法
-`OrderItemServiceImpl` 中实现了缓存逻辑
- 将查询结果以JSON格式存储到Redis过期时间为24小时
### 3. 定时任务
- 创建了 `OrderScheduledTask` 定时任务类
- 使用 `@Scheduled(cron = "0 0 12 * * ?")` 配置每天12点执行
- 在主应用类 `DromaraApplication` 上已添加了 `@EnableScheduling` 注解
### 4. 控制器接口
- 添加了手动触发缓存的接口:`POST /oms/order/cacheTopTradingProducts`
- 添加了获取缓存数据的接口:`GET /oms/order/getTopTradingProducts`
## 使用方法
### 1. 自动执行
定时任务会在每天12点自动执行无需手动干预。
### 2. 手动触发
如果需要立即执行缓存任务,可以调用以下接口:
```bash
POST /oms/order/cacheTopTradingProducts?limit=100
```
参数说明:
- `limit`: 查询的商品数量默认为100
### 3. 查看缓存结果
可以通过以下接口查看缓存的数据:
```bash
GET /oms/order/getTopTradingProducts
GET /oms/order/getTopTradingProducts?date=2024-01-15
```
参数说明:
- `date`: 可选指定查看某一天的缓存数据格式为yyyy-MM-dd
### 4. 返回数据格式
缓存的数据包含以下字段:
- `product_id`: 商品ID
- `product_name`: 商品名称
- `pic`: 商品图片
- `out_product_id`: 商品编码
- `product_category_id`: 商品分类ID
- `total_quantity`: 总销售数量
- `total_amount`: 总销售金额
- `order_count`: 订单数量
## 技术实现
### 1. SQL查询逻辑
```sql
SELECT
oi.product_id,
oi.product_name,
oi.pic,
oi.out_product_id,
oi.product_category_id,
SUM(oi.quantity) as total_quantity,
SUM(oi.quantity * oi.sale_price) as total_amount,
COUNT(DISTINCT o.id) as order_count
FROM oms_order_item oi
JOIN oms_order o ON oi.order_id = o.id
WHERE o.status = 3 -- 已完成订单
AND o.delete_status = 0 -- 未删除订单
GROUP BY oi.product_id, oi.product_name, oi.pic, oi.out_product_id, oi.product_category_id
ORDER BY total_quantity DESC
LIMIT #{limit}
```
### 2. Redis缓存
- Key格式`top_trading_products:yyyy-MM-dd`
- 过期时间24小时
- 数据格式JSON字符串
### 3. 异常处理
- 完善的异常处理和日志记录
- 手动触发接口返回详细的错误信息
- 定时任务异常不会影响系统正常运行
## 注意事项
1. **数据准确性**:只统计已完成订单的商品,确保数据的准确性
2. **性能考虑**:大量订单数据时,查询可能需要较长时间
3. **缓存更新**每天12点自动更新也可手动触发
4. **数据过期**缓存数据24小时自动过期避免数据过期问题
## 扩展功能
如需扩展功能,可以考虑:
1. 按时间范围统计如最近7天、30天
2. 按商品分类统计
3. 添加更多统计维度(如销售额、利润率等)
4. 支持多租户数据隔离