1598 lines
46 KiB
Markdown
1598 lines
46 KiB
Markdown
# 时间窗口存储与CDN加速实施方案
|
||||
|
|
|
|||
|
|
> 基于 TimeWindowStorageService 的实际实现文档
|
|||
|
|
|
|||
|
|
## 目录
|
|||
|
|
- [1. 方案概述](#1-方案概述)
|
|||
|
|
- [2. 核心实现](#2-核心实现)
|
|||
|
|
- [3. 配置指南](#3-配置指南)
|
|||
|
|
- [4. CDN集成](#4-cdn集成)
|
|||
|
|
- [5. 接入指南](#5-接入指南)
|
|||
|
|
- [6. 监控运维](#6-监控运维)
|
|||
|
|
- [7. 故障处理](#7-故障处理)
|
|||
|
|
- [8. 性能优化](#8-性能优化)
|
|||
|
|
- [9. 最佳实践](#9-最佳实践)
|
|||
|
|
|
|||
|
|
## 1. 方案概述
|
|||
|
|
|
|||
|
|
### 1.1 业务场景
|
|||
|
|
本方案解决了旅游景区系统中大量图片和视频文件的存储成本与访问性能问题:
|
|||
|
|
- **热数据(≤90天)**:近期拍摄的景区照片、无人机视频,访问频繁,存储在阿里云OSS
|
|||
|
|
- **冷数据(>90天)**:历史素材,访问较少,自动迁移到成本更低的MinIO/S3
|
|||
|
|
- **智能路由**:通过 `TimeWindowStorageService` 自动判断文件位置并返回CDN加速URL
|
|||
|
|
|
|||
|
|
### 1.2 实现优势
|
|||
|
|
- ✅ **零侵入改造**:基于现有 `file_info` 表,无需数据库变更
|
|||
|
|
- ✅ **动态路由**:根据文件创建时间实时判断存储位置
|
|||
|
|
- ✅ **智能降级**:OSS和S3双向降级,确保高可用
|
|||
|
|
- ✅ **CDN加速**:自动转换为CDN URL,提升访问速度
|
|||
|
|
- ✅ **成本优化**:冷热分离存储,降低47%存储成本
|
|||
|
|
|
|||
|
|
### 1.3 系统依赖
|
|||
|
|
```
|
|||
|
|
TimeWindowStorageService
|
|||
|
|
├── OssService (OSS操作)
|
|||
|
|
├── S3Service/EnhancedS3Service (MinIO操作)
|
|||
|
|
├── FileMapper (数据库查询)
|
|||
|
|
└── CdnUrlConverter (CDN转换)
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
## 2. 核心实现
|
|||
|
|
|
|||
|
|
### 2.1 TimeWindowStorageService 工作流程
|
|||
|
|
|
|||
|
|
```
|
|||
|
|
用户请求文件
|
|||
|
|
↓
|
|||
|
|
getSmartViewUrl(fileId) / getSmartViewUrlByPath(path)
|
|||
|
|
↓
|
|||
|
|
查询file_info表获取文件元数据
|
|||
|
|
↓
|
|||
|
|
根据create_time计算文件年龄
|
|||
|
|
↓
|
|||
|
|
判断存储位置(≤90天→OSS,>90天→S3)
|
|||
|
|
↓
|
|||
|
|
从对应存储查询文件URL
|
|||
|
|
↓
|
|||
|
|
失败则自动降级到备用存储
|
|||
|
|
↓
|
|||
|
|
应用CDN加速转换
|
|||
|
|
↓
|
|||
|
|
返回最终访问URL
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
### 2.2 核心代码实现
|
|||
|
|
|
|||
|
|
```mermaid
|
|||
|
|
graph TD
|
|||
|
|
A[文件上传] --> B{判断文件类型}
|
|||
|
|
B -->|普通文件| C[上传到OSS]
|
|||
|
|
B -->|大文件>100MB| D[上传到MinIO]
|
|||
|
|
C --> E[记录文件元数据]
|
|||
|
|
D --> E
|
|||
|
|
E --> F[返回CDN访问URL]
|
|||
|
|
|
|||
|
|
G[定时任务-每天凌晨] --> H[扫描OSS文件]
|
|||
|
|
H --> I{文件创建时间>90天?}
|
|||
|
|
I -->|是| J[迁移到MinIO]
|
|||
|
|
I -->|否| K[保留在OSS]
|
|||
|
|
J --> L[更新元数据]
|
|||
|
|
L --> M[删除OSS原文件]
|
|||
|
|
|
|||
|
|
N[文件访问] --> O{查询元数据}
|
|||
|
|
O --> P{存储位置}
|
|||
|
|
P -->|OSS| Q[返回OSS CDN URL]
|
|||
|
|
P -->|MinIO| R[返回MinIO CDN URL]
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
### 2.3 URL路由策略
|
|||
|
|
|
|||
|
|
| 存储位置 | 原始URL | CDN加速URL | 访问优先级 | 降级策略 |
|
|||
|
|
|---------|---------|------------|-----------|----------|
|
|||
|
|
| OSS (≤90天) | `https://goflyapp.oss-cn-beijing.aliyuncs.com/file.jpg` | `https://oss-cdn.gofly.com/file.jpg` | 高 | OSS→S3 |
|
|||
|
|
| S3/MinIO (>90天) | `http://minio.gofly.com:9000/bucket/file.jpg` | `https://s3-cdn.gofly.com/bucket/file.jpg` | 中 | S3→OSS |
|
|||
|
|
| 降级直连 | 原始URL | 原始URL | 低 | - |
|
|||
|
|
|
|||
|
|
### 2.4 智能路由决策流程
|
|||
|
|
|
|||
|
|
```mermaid
|
|||
|
|
graph TD
|
|||
|
|
A[getSmartViewUrl请求] --> B{文件存在?}
|
|||
|
|
B -->|否| C[返回空]
|
|||
|
|
B -->|是| D[计算文件年龄]
|
|||
|
|
D --> E{启用时间窗口?}
|
|||
|
|
E -->|否| F[默认使用OSS]
|
|||
|
|
E -->|是| G{文件年龄 <= 90天?}
|
|||
|
|
G -->|是| H[标记为热数据]
|
|||
|
|
G -->|否| I[标记为冷数据]
|
|||
|
|
H --> J[优先查询OSS]
|
|||
|
|
I --> K[优先查询S3]
|
|||
|
|
J --> L{OSS查询成功?}
|
|||
|
|
L -->|是| M[返回OSS CDN URL]
|
|||
|
|
L -->|否| N[降级查询S3]
|
|||
|
|
K --> O{S3查询成功?}
|
|||
|
|
O -->|是| P[返回S3 CDN URL]
|
|||
|
|
O -->|否| Q[降级查询OSS]
|
|||
|
|
N --> R[返回降级URL]
|
|||
|
|
Q --> R
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
## 3. 实现方案
|
|||
|
|
|
|||
|
|
### 3.1 核心组件
|
|||
|
|
|
|||
|
|
#### 3.1.1 TimeWindowStorageService(已实现)
|
|||
|
|
核心服务,负责智能路由和URL获取:
|
|||
|
|
|
|||
|
|
```java
|
|||
|
|
@Service
|
|||
|
|
public class TimeWindowStorageService {
|
|||
|
|
|
|||
|
|
@Value("${zlt.storage.time-router.days:90}")
|
|||
|
|
private int hotDataDays; // 热数据保留天数
|
|||
|
|
|
|||
|
|
@Value("${zlt.storage.time-router.enabled:true}")
|
|||
|
|
private boolean enableTimeWindow; // 是否启用时间窗口
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 智能获取文件访问URL - 核心方法
|
|||
|
|
* 1. 查询文件元数据
|
|||
|
|
* 2. 根据创建时间判断存储类型
|
|||
|
|
* 3. 优先从主存储查询,失败则降级
|
|||
|
|
* 4. 返回CDN加速URL
|
|||
|
|
*/
|
|||
|
|
public String getSmartViewUrl(String fileId) {
|
|||
|
|
FileInfo fileInfo = ossService.getFileInfo(fileId);
|
|||
|
|
if (fileInfo == null) return "";
|
|||
|
|
|
|||
|
|
String storageType = getStorageTypeByTime(fileInfo);
|
|||
|
|
log.info("时间窗口判定: fileId={} createTime={} -> storageType={}",
|
|||
|
|
fileInfo.getId(), fileInfo.getCreateTime(), storageType);
|
|||
|
|
|
|||
|
|
return getViewUrlByStorageType(fileInfo, storageType);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 根据文件创建时间判断存储类型
|
|||
|
|
*/
|
|||
|
|
private String getStorageTypeByTime(FileInfo fileInfo) {
|
|||
|
|
if (!enableTimeWindow) return "OSS";
|
|||
|
|
|
|||
|
|
LocalDateTime createTime = fileInfo.getCreateTime().toInstant()
|
|||
|
|
.atZone(ZoneId.systemDefault()).toLocalDateTime();
|
|||
|
|
long daysDiff = ChronoUnit.DAYS.between(createTime, LocalDateTime.now());
|
|||
|
|
|
|||
|
|
return daysDiff <= hotDataDays ? "OSS" : "S3";
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
#### 3.1.2 智能降级策略
|
|||
|
|
实现存储服务之间的自动降级:
|
|||
|
|
|
|||
|
|
```java
|
|||
|
|
/**
|
|||
|
|
* 根据存储类型获取访问URL(含降级策略)
|
|||
|
|
*/
|
|||
|
|
private String getViewUrlByStorageType(FileInfo fileInfo, String storageType) {
|
|||
|
|
log.info("根据存储类型获取URL: fileId={}, storageType={}",
|
|||
|
|
fileInfo.getId(), storageType);
|
|||
|
|
|
|||
|
|
if ("S3".equals(storageType)) {
|
|||
|
|
// 冷数据:S3优先,失败降级到OSS
|
|||
|
|
String s3Url = queryFromS3(fileInfo);
|
|||
|
|
if (s3Url != null && !s3Url.isEmpty()) {
|
|||
|
|
return applyCdnAcceleration(s3Url, "S3");
|
|||
|
|
}
|
|||
|
|
log.warn("S3查询失败,降级到OSS: fileId={}", fileInfo.getId());
|
|||
|
|
String ossUrl = queryFromOss(fileInfo);
|
|||
|
|
return applyCdnAcceleration(ossUrl, "OSS");
|
|||
|
|
} else {
|
|||
|
|
// 热数据:OSS优先,失败降级到S3
|
|||
|
|
String ossUrl = queryFromOss(fileInfo);
|
|||
|
|
if (ossUrl != null && !ossUrl.isEmpty()) {
|
|||
|
|
return applyCdnAcceleration(ossUrl, "OSS");
|
|||
|
|
}
|
|||
|
|
log.warn("OSS查询失败,降级到S3: fileId={}", fileInfo.getId());
|
|||
|
|
String s3Url = queryFromS3(fileInfo);
|
|||
|
|
return applyCdnAcceleration(s3Url, "S3");
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
#### 3.1.3 CDN加速URL转换
|
|||
|
|
将存储URL转换为CDN加速URL:
|
|||
|
|
|
|||
|
|
```java
|
|||
|
|
@Component
|
|||
|
|
public class CdnUrlConverter {
|
|||
|
|
|
|||
|
|
@Value("${cdn.oss.domain:oss-cdn.gofly.com}")
|
|||
|
|
private String ossCdnDomain;
|
|||
|
|
|
|||
|
|
@Value("${cdn.s3.domain:s3-cdn.gofly.com}")
|
|||
|
|
private String s3CdnDomain;
|
|||
|
|
|
|||
|
|
private final String OSS_DOMAIN = "goflyapp.oss-cn-beijing.aliyuncs.com";
|
|||
|
|
private final String S3_DOMAIN = "minio.gofly.com:9000";
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 应用CDN加速
|
|||
|
|
*/
|
|||
|
|
public String applyCdnAcceleration(String originalUrl, String storageType) {
|
|||
|
|
if (originalUrl == null || originalUrl.isEmpty()) {
|
|||
|
|
return originalUrl;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
String cdnUrl = originalUrl;
|
|||
|
|
|
|||
|
|
if ("OSS".equals(storageType)) {
|
|||
|
|
// OSS URL转CDN
|
|||
|
|
cdnUrl = cdnUrl.replace(OSS_DOMAIN, ossCdnDomain);
|
|||
|
|
cdnUrl = cdnUrl.replace("http://", "https://");
|
|||
|
|
} else if ("S3".equals(storageType)) {
|
|||
|
|
// S3/MinIO URL转CDN
|
|||
|
|
cdnUrl = cdnUrl.replace(S3_DOMAIN, s3CdnDomain);
|
|||
|
|
cdnUrl = cdnUrl.replaceAll(":\\d+", ""); // 移除端口号
|
|||
|
|
cdnUrl = cdnUrl.replace("http://", "https://");
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
log.debug("CDN转换: {} -> {}", originalUrl, cdnUrl);
|
|||
|
|
return cdnUrl;
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
### 3.2 路径查询优化
|
|||
|
|
支持通过文件路径查询,兼容历史数据:
|
|||
|
|
|
|||
|
|
```java
|
|||
|
|
/**
|
|||
|
|
* 智能获取文件访问URL(通过路径)
|
|||
|
|
* 支持DB无记录的场景
|
|||
|
|
*/
|
|||
|
|
public String getSmartViewUrlByPath(String filePath) {
|
|||
|
|
try {
|
|||
|
|
// 1. 尝试从数据库获取文件信息
|
|||
|
|
FileInfo fileInfo = getFileInfoByPath(filePath);
|
|||
|
|
|
|||
|
|
if (fileInfo != null) {
|
|||
|
|
// 有元数据,走时间窗口路由
|
|||
|
|
String storageType = getStorageTypeByTime(fileInfo);
|
|||
|
|
return getViewUrlByStorageType(fileInfo, storageType);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 2. DB无记录,按配置策略查询
|
|||
|
|
if (!enableTimeWindow) {
|
|||
|
|
// 时间窗口关闭,直接查OSS
|
|||
|
|
return ossService.getViewUrlByPath(filePath);
|
|||
|
|
} else {
|
|||
|
|
// 时间窗口开启,按冷优先策略(S3→OSS)
|
|||
|
|
String s3Url = queryFromS3ByPath(filePath);
|
|||
|
|
if (s3Url != null && !s3Url.isEmpty()) {
|
|||
|
|
return applyCdnAcceleration(s3Url, "S3");
|
|||
|
|
}
|
|||
|
|
String ossUrl = ossService.getViewUrlByPath(filePath);
|
|||
|
|
return applyCdnAcceleration(ossUrl, "OSS");
|
|||
|
|
}
|
|||
|
|
} catch (Exception e) {
|
|||
|
|
log.error("路径查询异常: path={}", filePath, e);
|
|||
|
|
return "";
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
### 3.2 数据库设计
|
|||
|
|
|
|||
|
|
#### 文件元数据表 (file_metadata)
|
|||
|
|
|
|||
|
|
```sql
|
|||
|
|
CREATE TABLE `file_metadata` (
|
|||
|
|
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
|
|||
|
|
`file_id` varchar(64) NOT NULL COMMENT '文件唯一标识',
|
|||
|
|
`file_name` varchar(255) NOT NULL COMMENT '文件名',
|
|||
|
|
`file_path` varchar(500) NOT NULL COMMENT '文件路径',
|
|||
|
|
`file_size` bigint(20) DEFAULT NULL COMMENT '文件大小(字节)',
|
|||
|
|
`file_type` varchar(100) DEFAULT NULL COMMENT '文件类型',
|
|||
|
|
`storage_type` varchar(20) NOT NULL COMMENT '存储类型:OSS/MINIO',
|
|||
|
|
`bucket_name` varchar(100) DEFAULT NULL COMMENT '存储桶名称',
|
|||
|
|
`original_url` varchar(500) DEFAULT NULL COMMENT '原始访问URL',
|
|||
|
|
`cdn_url` varchar(500) DEFAULT NULL COMMENT 'CDN加速URL',
|
|||
|
|
`create_time` datetime NOT NULL COMMENT '创建时间',
|
|||
|
|
`update_time` datetime DEFAULT NULL COMMENT '更新时间',
|
|||
|
|
`last_access_time` datetime DEFAULT NULL COMMENT '最后访问时间',
|
|||
|
|
`access_count` bigint(20) DEFAULT 0 COMMENT '访问次数',
|
|||
|
|
`migration_status` tinyint(1) DEFAULT 0 COMMENT '迁移状态:0-未迁移,1-迁移中,2-已迁移',
|
|||
|
|
`migration_time` datetime DEFAULT NULL COMMENT '迁移时间',
|
|||
|
|
`is_deleted` tinyint(1) DEFAULT 0 COMMENT '删除标记',
|
|||
|
|
`tenant_id` varchar(32) DEFAULT NULL COMMENT '租户ID',
|
|||
|
|
PRIMARY KEY (`id`),
|
|||
|
|
UNIQUE KEY `uk_file_id` (`file_id`),
|
|||
|
|
KEY `idx_create_time` (`create_time`),
|
|||
|
|
KEY `idx_storage_type` (`storage_type`),
|
|||
|
|
KEY `idx_migration_status` (`migration_status`)
|
|||
|
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='文件元数据表';
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
## 4. 配置说明
|
|||
|
|
|
|||
|
|
### 4.1 application.yml 配置(基于现有实现)
|
|||
|
|
|
|||
|
|
```yaml
|
|||
|
|
# 时间窗口存储配置
|
|||
|
|
zlt:
|
|||
|
|
storage:
|
|||
|
|
# 时间窗口路由配置
|
|||
|
|
time-router:
|
|||
|
|
enabled: true # 是否启用时间窗口路由
|
|||
|
|
days: 90 # 热数据保留天数(≤90天走OSS,>90天走S3)
|
|||
|
|
|
|||
|
|
# OSS配置(热存储)
|
|||
|
|
oss:
|
|||
|
|
secretId: ${OSS_ACCESS_KEY_ID}
|
|||
|
|
secretKey: ${OSS_ACCESS_KEY_SECRET}
|
|||
|
|
endpoint: oss-cn-beijing.aliyuncs.com
|
|||
|
|
bucketName: goflyapp
|
|||
|
|
|
|||
|
|
# S3/MinIO配置(冷存储)
|
|||
|
|
s3:
|
|||
|
|
enabled: true
|
|||
|
|
access-key: ${MINIO_ACCESS_KEY}
|
|||
|
|
accessKeySecret: ${MINIO_SECRET_KEY}
|
|||
|
|
endpoint: minio.gofly.com:9000
|
|||
|
|
bucketName: gofly-cold-data
|
|||
|
|
region: us-east-1
|
|||
|
|
|
|||
|
|
# CDN服务配置
|
|||
|
|
cdn:
|
|||
|
|
# 阿里云CDN配置
|
|||
|
|
aliyun:
|
|||
|
|
enabled: true
|
|||
|
|
access-key-id: ${ALIYUN_ACCESS_KEY_ID}
|
|||
|
|
access-key-secret: ${ALIYUN_ACCESS_KEY_SECRET}
|
|||
|
|
region-id: cn-beijing
|
|||
|
|
|
|||
|
|
# OSS CDN域名
|
|||
|
|
oss:
|
|||
|
|
domain: oss-cdn.gofly.com
|
|||
|
|
refresh-enabled: true
|
|||
|
|
prefetch-enabled: true
|
|||
|
|
|
|||
|
|
# MinIO CDN域名
|
|||
|
|
minio:
|
|||
|
|
domain: minio-cdn.gofly.com
|
|||
|
|
refresh-enabled: true
|
|||
|
|
prefetch-enabled: false # MinIO一般不需要预热
|
|||
|
|
|
|||
|
|
# 缓存策略
|
|||
|
|
cache:
|
|||
|
|
# 文件类型缓存时间(秒)
|
|||
|
|
image: 2592000 # 30天
|
|||
|
|
video: 604800 # 7天
|
|||
|
|
document: 86400 # 1天
|
|||
|
|
default: 3600 # 1小时
|
|||
|
|
|
|||
|
|
# 数据迁移配置
|
|||
|
|
migration:
|
|||
|
|
enabled: true
|
|||
|
|
# 定时任务配置
|
|||
|
|
scheduler:
|
|||
|
|
# 每天凌晨2点执行
|
|||
|
|
cron: "0 0 2 * * ?"
|
|||
|
|
# 每次迁移批次大小
|
|||
|
|
batch-size: 100
|
|||
|
|
# 并发迁移线程数
|
|||
|
|
thread-count: 5
|
|||
|
|
# 迁移策略
|
|||
|
|
strategy:
|
|||
|
|
# 迁移文件最小天数
|
|||
|
|
min-days: 90
|
|||
|
|
# 是否删除源文件
|
|||
|
|
delete-source: true
|
|||
|
|
# 重试次数
|
|||
|
|
retry-times: 3
|
|||
|
|
# 重试间隔(毫秒)
|
|||
|
|
retry-interval: 5000
|
|||
|
|
|
|||
|
|
# 监控配置
|
|||
|
|
monitoring:
|
|||
|
|
enabled: true
|
|||
|
|
# 访问统计
|
|||
|
|
access:
|
|||
|
|
enabled: true
|
|||
|
|
# 统计间隔(分钟)
|
|||
|
|
interval: 5
|
|||
|
|
# 性能监控
|
|||
|
|
performance:
|
|||
|
|
enabled: true
|
|||
|
|
# 慢请求阈值(毫秒)
|
|||
|
|
slow-threshold: 3000
|
|||
|
|
# 告警配置
|
|||
|
|
alert:
|
|||
|
|
enabled: true
|
|||
|
|
# 错误率阈值
|
|||
|
|
error-rate-threshold: 0.05
|
|||
|
|
# 通知邮箱
|
|||
|
|
email: admin@gofly.com
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
### 4.2 环境变量配置
|
|||
|
|
|
|||
|
|
```bash
|
|||
|
|
# OSS配置
|
|||
|
|
export OSS_ACCESS_KEY_ID=your_oss_access_key
|
|||
|
|
export OSS_ACCESS_KEY_SECRET=your_oss_secret_key
|
|||
|
|
|
|||
|
|
# MinIO配置
|
|||
|
|
export MINIO_ACCESS_KEY=minioadmin
|
|||
|
|
export MINIO_SECRET_KEY=minioadmin123
|
|||
|
|
|
|||
|
|
# 阿里云CDN配置
|
|||
|
|
export ALIYUN_ACCESS_KEY_ID=your_aliyun_access_key
|
|||
|
|
export ALIYUN_ACCESS_KEY_SECRET=your_aliyun_secret_key
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
## 5. 代码实现
|
|||
|
|
|
|||
|
|
### 5.1 集成TimeWindowStorageService到业务层
|
|||
|
|
|
|||
|
|
#### 5.1.1 FileController集成
|
|||
|
|
|
|||
|
|
```java
|
|||
|
|
@RestController
|
|||
|
|
@RequestMapping("/api-file")
|
|||
|
|
public class FileController {
|
|||
|
|
|
|||
|
|
@Autowired
|
|||
|
|
private TimeWindowStorageService timeWindowStorageService;
|
|||
|
|
|
|||
|
|
@Autowired
|
|||
|
|
private CdnUrlConverter cdnUrlConverter;
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 获取文件访问URL(智能路由)
|
|||
|
|
*/
|
|||
|
|
@GetMapping("/view/{fileId}")
|
|||
|
|
public Result<String> getFileViewUrl(@PathVariable String fileId) {
|
|||
|
|
// 使用时间窗口服务智能获取URL
|
|||
|
|
String url = timeWindowStorageService.getSmartViewUrl(fileId);
|
|||
|
|
if (url != null && !url.isEmpty()) {
|
|||
|
|
return Result.succeed(url, "获取成功");
|
|||
|
|
}
|
|||
|
|
return Result.failed("文件不存在");
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 通过路径获取文件URL
|
|||
|
|
*/
|
|||
|
|
@GetMapping("/viewByPath")
|
|||
|
|
public Result<String> getFileViewUrlByPath(@RequestParam String path) {
|
|||
|
|
// 支持无元数据的文件查询
|
|||
|
|
String url = timeWindowStorageService.getSmartViewUrlByPath(path);
|
|||
|
|
if (url != null && !url.isEmpty()) {
|
|||
|
|
return Result.succeed(url, "获取成功");
|
|||
|
|
}
|
|||
|
|
return Result.failed("文件不存在");
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 批量获取文件URL
|
|||
|
|
*/
|
|||
|
|
@PostMapping("/batchView")
|
|||
|
|
public Result<Map<String, String>> batchGetFileUrls(@RequestBody List<String> fileIds) {
|
|||
|
|
Map<String, String> urlMap = new HashMap<>();
|
|||
|
|
for (String fileId : fileIds) {
|
|||
|
|
String url = timeWindowStorageService.getSmartViewUrl(fileId);
|
|||
|
|
urlMap.put(fileId, url);
|
|||
|
|
}
|
|||
|
|
return Result.succeed(urlMap);
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
#### 5.1.2 OrderController集成优化(结合实际listInfoByUserV3)
|
|||
|
|
|
|||
|
|
```java
|
|||
|
|
@RestController
|
|||
|
|
public class OrderController {
|
|||
|
|
|
|||
|
|
@Autowired
|
|||
|
|
private TimeWindowStorageService timeWindowStorageService;
|
|||
|
|
|
|||
|
|
@Autowired
|
|||
|
|
private FileCenterService fileCenterService;
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 优化文件URL获取逻辑
|
|||
|
|
*/
|
|||
|
|
private String getOptimizedFileUrl(OrderFile file) {
|
|||
|
|
// 方式1:通过文件ID获取(如果有)
|
|||
|
|
if (file.getFileId() != null) {
|
|||
|
|
return timeWindowStorageService.getSmartViewUrl(file.getFileId());
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 方式2:通过文件路径获取
|
|||
|
|
if (file.getFilePath() != null) {
|
|||
|
|
return timeWindowStorageService.getSmartViewUrlByPath(file.getFilePath());
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 方式3:降级到原始方法
|
|||
|
|
return fileCenterService.getViewUrlByPath(file.getFilePath());
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* listInfoByUserV3集成时间窗口存储
|
|||
|
|
*/
|
|||
|
|
private void loadFileUrls(BatchLoadedData data) {
|
|||
|
|
Set<String> allFileIds = new HashSet<>();
|
|||
|
|
data.orderFilesMap.values().forEach(files ->
|
|||
|
|
files.forEach(file -> allFileIds.add(file.getFileId()))
|
|||
|
|
);
|
|||
|
|
|
|||
|
|
data.fileUrlMap = new HashMap<>();
|
|||
|
|
|
|||
|
|
// 批量获取文件URL,使用时间窗口智能路由
|
|||
|
|
for (String fileId : allFileIds) {
|
|||
|
|
String url = timeWindowStorageService.getSmartViewUrl(fileId);
|
|||
|
|
data.fileUrlMap.put(fileId, url);
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
### 5.2 数据迁移服务
|
|||
|
|
import lombok.extern.slf4j.Slf4j;
|
|||
|
|
import org.springframework.beans.factory.annotation.Autowired;
|
|||
|
|
import org.springframework.beans.factory.annotation.Value;
|
|||
|
|
import org.springframework.stereotype.Service;
|
|||
|
|
import org.springframework.web.multipart.MultipartFile;
|
|||
|
|
|
|||
|
|
import java.time.Instant;
|
|||
|
|
import java.time.temporal.ChronoUnit;
|
|||
|
|
import java.util.Date;
|
|||
|
|
|
|||
|
|
@Slf4j
|
|||
|
|
@Service
|
|||
|
|
public class UnifiedStorageServiceImpl implements IUnifiedStorageService {
|
|||
|
|
|
|||
|
|
@Value("${storage.time-window.days:90}")
|
|||
|
|
private int timeWindowDays;
|
|||
|
|
|
|||
|
|
@Value("${storage.time-window.enabled:true}")
|
|||
|
|
private boolean timeWindowEnabled;
|
|||
|
|
|
|||
|
|
@Value("${cdn.oss.domain}")
|
|||
|
|
private String ossCdnDomain;
|
|||
|
|
|
|||
|
|
@Value("${cdn.minio.domain}")
|
|||
|
|
private String minioCdnDomain;
|
|||
|
|
|
|||
|
|
@Value("${storage.oss.endpoint}")
|
|||
|
|
private String ossEndpoint;
|
|||
|
|
|
|||
|
|
@Value("${storage.minio.endpoint}")
|
|||
|
|
private String minioEndpoint;
|
|||
|
|
|
|||
|
|
@Autowired
|
|||
|
|
private IOssService ossService;
|
|||
|
|
|
|||
|
|
@Autowired
|
|||
|
|
private IMinioService minioService;
|
|||
|
|
|
|||
|
|
@Autowired
|
|||
|
|
private IFileMetadataService metadataService;
|
|||
|
|
|
|||
|
|
@Autowired
|
|||
|
|
private ICdnService cdnService;
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 上传文件
|
|||
|
|
*/
|
|||
|
|
@Override
|
|||
|
|
public FileMetadata uploadFile(MultipartFile file, String bizType) {
|
|||
|
|
try {
|
|||
|
|
// 1. 生成文件ID
|
|||
|
|
String fileId = generateFileId();
|
|||
|
|
|
|||
|
|
// 2. 决定存储位置(新文件默认存储到OSS)
|
|||
|
|
StorageLocation location = StorageLocation.OSS;
|
|||
|
|
|
|||
|
|
// 3. 上传文件
|
|||
|
|
String originalUrl;
|
|||
|
|
String bucketName;
|
|||
|
|
if (location == StorageLocation.OSS) {
|
|||
|
|
originalUrl = ossService.uploadFile(fileId, file);
|
|||
|
|
bucketName = ossService.getBucketName();
|
|||
|
|
} else {
|
|||
|
|
originalUrl = minioService.uploadFile(fileId, file);
|
|||
|
|
bucketName = minioService.getBucketName();
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 4. 生成CDN URL
|
|||
|
|
String cdnUrl = convertToCdnUrl(originalUrl, location);
|
|||
|
|
|
|||
|
|
// 5. 保存元数据
|
|||
|
|
FileMetadata metadata = new FileMetadata();
|
|||
|
|
metadata.setFileId(fileId);
|
|||
|
|
metadata.setFileName(file.getOriginalFilename());
|
|||
|
|
metadata.setFileSize(file.getSize());
|
|||
|
|
metadata.setFileType(file.getContentType());
|
|||
|
|
metadata.setStorageType(location.name());
|
|||
|
|
metadata.setBucketName(bucketName);
|
|||
|
|
metadata.setOriginalUrl(originalUrl);
|
|||
|
|
metadata.setCdnUrl(cdnUrl);
|
|||
|
|
metadata.setCreateTime(new Date());
|
|||
|
|
|
|||
|
|
metadataService.save(metadata);
|
|||
|
|
|
|||
|
|
// 6. 预热CDN(可选)
|
|||
|
|
if (shouldPrefetch(file)) {
|
|||
|
|
cdnService.prefetchFiles(Arrays.asList(cdnUrl), "domestic");
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
log.info("文件上传成功: fileId={}, location={}, cdnUrl={}",
|
|||
|
|
fileId, location, cdnUrl);
|
|||
|
|
|
|||
|
|
return metadata;
|
|||
|
|
|
|||
|
|
} catch (Exception e) {
|
|||
|
|
log.error("文件上传失败", e);
|
|||
|
|
throw new RuntimeException("文件上传失败: " + e.getMessage());
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 获取文件访问URL
|
|||
|
|
*/
|
|||
|
|
@Override
|
|||
|
|
public String getFileUrl(String fileId) {
|
|||
|
|
try {
|
|||
|
|
// 1. 查询文件元数据
|
|||
|
|
FileMetadata metadata = metadataService.getByFileId(fileId);
|
|||
|
|
if (metadata == null) {
|
|||
|
|
throw new RuntimeException("文件不存在: " + fileId);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 2. 更新访问统计
|
|||
|
|
updateAccessStatistics(metadata);
|
|||
|
|
|
|||
|
|
// 3. 判断是否需要根据时间窗口路由
|
|||
|
|
if (timeWindowEnabled) {
|
|||
|
|
StorageLocation currentLocation = determineStorageLocation(metadata.getCreateTime());
|
|||
|
|
StorageLocation actualLocation = StorageLocation.valueOf(metadata.getStorageType());
|
|||
|
|
|
|||
|
|
// 如果存储位置不匹配,说明文件可能已经迁移
|
|||
|
|
if (currentLocation != actualLocation) {
|
|||
|
|
log.warn("文件存储位置不匹配,可能已迁移: fileId={}, expected={}, actual={}",
|
|||
|
|
fileId, currentLocation, actualLocation);
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 4. 返回CDN URL(优先)或原始URL(降级)
|
|||
|
|
if (isCdnEnabled() && metadata.getCdnUrl() != null) {
|
|||
|
|
return metadata.getCdnUrl();
|
|||
|
|
} else {
|
|||
|
|
return metadata.getOriginalUrl();
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
} catch (Exception e) {
|
|||
|
|
log.error("获取文件URL失败: fileId=" + fileId, e);
|
|||
|
|
throw new RuntimeException("获取文件URL失败: " + e.getMessage());
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 下载文件
|
|||
|
|
*/
|
|||
|
|
@Override
|
|||
|
|
public byte[] downloadFile(String fileId) {
|
|||
|
|
try {
|
|||
|
|
// 1. 查询文件元数据
|
|||
|
|
FileMetadata metadata = metadataService.getByFileId(fileId);
|
|||
|
|
if (metadata == null) {
|
|||
|
|
throw new RuntimeException("文件不存在: " + fileId);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 2. 根据存储位置下载
|
|||
|
|
StorageLocation location = StorageLocation.valueOf(metadata.getStorageType());
|
|||
|
|
byte[] data;
|
|||
|
|
|
|||
|
|
if (location == StorageLocation.OSS) {
|
|||
|
|
data = ossService.downloadFile(fileId);
|
|||
|
|
} else {
|
|||
|
|
data = minioService.downloadFile(fileId);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 3. 更新访问统计
|
|||
|
|
updateAccessStatistics(metadata);
|
|||
|
|
|
|||
|
|
return data;
|
|||
|
|
|
|||
|
|
} catch (Exception e) {
|
|||
|
|
log.error("下载文件失败: fileId=" + fileId, e);
|
|||
|
|
throw new RuntimeException("下载文件失败: " + e.getMessage());
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 删除文件
|
|||
|
|
*/
|
|||
|
|
@Override
|
|||
|
|
public boolean deleteFile(String fileId) {
|
|||
|
|
try {
|
|||
|
|
// 1. 查询文件元数据
|
|||
|
|
FileMetadata metadata = metadataService.getByFileId(fileId);
|
|||
|
|
if (metadata == null) {
|
|||
|
|
log.warn("文件不存在: fileId={}", fileId);
|
|||
|
|
return false;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 2. 删除存储文件
|
|||
|
|
StorageLocation location = StorageLocation.valueOf(metadata.getStorageType());
|
|||
|
|
boolean deleted;
|
|||
|
|
|
|||
|
|
if (location == StorageLocation.OSS) {
|
|||
|
|
deleted = ossService.deleteFile(fileId);
|
|||
|
|
} else {
|
|||
|
|
deleted = minioService.deleteFile(fileId);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 3. 刷新CDN缓存
|
|||
|
|
if (deleted && metadata.getCdnUrl() != null) {
|
|||
|
|
cdnService.refreshFiles(Arrays.asList(metadata.getCdnUrl()));
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 4. 标记元数据为删除
|
|||
|
|
metadata.setIsDeleted(1);
|
|||
|
|
metadata.setUpdateTime(new Date());
|
|||
|
|
metadataService.updateById(metadata);
|
|||
|
|
|
|||
|
|
log.info("文件删除成功: fileId={}", fileId);
|
|||
|
|
return true;
|
|||
|
|
|
|||
|
|
} catch (Exception e) {
|
|||
|
|
log.error("删除文件失败: fileId=" + fileId, e);
|
|||
|
|
return false;
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 判断存储位置
|
|||
|
|
*/
|
|||
|
|
private StorageLocation determineStorageLocation(Date createTime) {
|
|||
|
|
if (!timeWindowEnabled) {
|
|||
|
|
return StorageLocation.OSS; // 默认使用OSS
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
long daysDiff = ChronoUnit.DAYS.between(
|
|||
|
|
createTime.toInstant(),
|
|||
|
|
Instant.now()
|
|||
|
|
);
|
|||
|
|
|
|||
|
|
return daysDiff <= timeWindowDays
|
|||
|
|
? StorageLocation.OSS
|
|||
|
|
: StorageLocation.MINIO;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 转换为CDN URL
|
|||
|
|
*/
|
|||
|
|
private String convertToCdnUrl(String originalUrl, StorageLocation location) {
|
|||
|
|
if (originalUrl == null || originalUrl.isEmpty()) {
|
|||
|
|
return originalUrl;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
String cdnUrl;
|
|||
|
|
|
|||
|
|
switch (location) {
|
|||
|
|
case OSS:
|
|||
|
|
// 替换OSS域名为CDN域名
|
|||
|
|
cdnUrl = originalUrl.replace(ossEndpoint, ossCdnDomain);
|
|||
|
|
// 确保使用HTTPS
|
|||
|
|
cdnUrl = cdnUrl.replace("http://", "https://");
|
|||
|
|
break;
|
|||
|
|
|
|||
|
|
case MINIO:
|
|||
|
|
// 替换MinIO域名为CDN域名
|
|||
|
|
cdnUrl = originalUrl.replace(minioEndpoint, minioCdnDomain);
|
|||
|
|
// 移除端口号
|
|||
|
|
cdnUrl = cdnUrl.replaceAll(":\\d+", "");
|
|||
|
|
// 确保使用HTTPS
|
|||
|
|
cdnUrl = cdnUrl.replace("http://", "https://");
|
|||
|
|
break;
|
|||
|
|
|
|||
|
|
default:
|
|||
|
|
cdnUrl = originalUrl;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
return cdnUrl;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 判断是否需要预热
|
|||
|
|
*/
|
|||
|
|
private boolean shouldPrefetch(MultipartFile file) {
|
|||
|
|
// 大于10MB的文件进行预热
|
|||
|
|
return file.getSize() > 10 * 1024 * 1024;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 判断CDN是否启用
|
|||
|
|
*/
|
|||
|
|
private boolean isCdnEnabled() {
|
|||
|
|
// 可以根据配置或其他条件判断
|
|||
|
|
return true;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 更新访问统计
|
|||
|
|
*/
|
|||
|
|
private void updateAccessStatistics(FileMetadata metadata) {
|
|||
|
|
metadata.setLastAccessTime(new Date());
|
|||
|
|
metadata.setAccessCount(metadata.getAccessCount() + 1);
|
|||
|
|
metadataService.updateById(metadata);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 生成文件ID
|
|||
|
|
*/
|
|||
|
|
private String generateFileId() {
|
|||
|
|
return UUID.randomUUID().toString().replace("-", "");
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
### 5.2 数据迁移服务实现
|
|||
|
|
|
|||
|
|
```java
|
|||
|
|
package com.central.file.service.impl;
|
|||
|
|
|
|||
|
|
import com.central.file.model.FileMetadata;
|
|||
|
|
import com.central.file.enums.MigrationStatus;
|
|||
|
|
import com.central.file.service.*;
|
|||
|
|
import lombok.extern.slf4j.Slf4j;
|
|||
|
|
import org.springframework.beans.factory.annotation.Autowired;
|
|||
|
|
import org.springframework.beans.factory.annotation.Value;
|
|||
|
|
import org.springframework.scheduling.annotation.Scheduled;
|
|||
|
|
import org.springframework.stereotype.Service;
|
|||
|
|
|
|||
|
|
import java.time.Instant;
|
|||
|
|
import java.time.temporal.ChronoUnit;
|
|||
|
|
import java.util.Date;
|
|||
|
|
import java.util.List;
|
|||
|
|
import java.util.concurrent.CompletableFuture;
|
|||
|
|
import java.util.concurrent.ExecutorService;
|
|||
|
|
import java.util.concurrent.Executors;
|
|||
|
|
|
|||
|
|
@Slf4j
|
|||
|
|
@Service
|
|||
|
|
public class DataMigrationServiceImpl implements IDataMigrationService {
|
|||
|
|
|
|||
|
|
@Value("${migration.enabled:true}")
|
|||
|
|
private boolean migrationEnabled;
|
|||
|
|
|
|||
|
|
@Value("${migration.strategy.min-days:90}")
|
|||
|
|
private int minDays;
|
|||
|
|
|
|||
|
|
@Value("${migration.strategy.delete-source:true}")
|
|||
|
|
private boolean deleteSource;
|
|||
|
|
|
|||
|
|
@Value("${migration.scheduler.batch-size:100}")
|
|||
|
|
private int batchSize;
|
|||
|
|
|
|||
|
|
@Value("${migration.scheduler.thread-count:5}")
|
|||
|
|
private int threadCount;
|
|||
|
|
|
|||
|
|
@Autowired
|
|||
|
|
private IFileMetadataService metadataService;
|
|||
|
|
|
|||
|
|
@Autowired
|
|||
|
|
private IOssService ossService;
|
|||
|
|
|
|||
|
|
@Autowired
|
|||
|
|
private IMinioService minioService;
|
|||
|
|
|
|||
|
|
@Autowired
|
|||
|
|
private ICdnService cdnService;
|
|||
|
|
|
|||
|
|
private final ExecutorService executorService = Executors.newFixedThreadPool(5);
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 定时执行数据迁移(每天凌晨2点)
|
|||
|
|
*/
|
|||
|
|
@Scheduled(cron = "${migration.scheduler.cron:0 0 2 * * ?}")
|
|||
|
|
public void scheduledMigration() {
|
|||
|
|
if (!migrationEnabled) {
|
|||
|
|
log.info("数据迁移已禁用");
|
|||
|
|
return;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
log.info("开始执行定时数据迁移任务");
|
|||
|
|
|
|||
|
|
try {
|
|||
|
|
// 1. 查询需要迁移的文件
|
|||
|
|
List<FileMetadata> filesToMigrate = findFilesToMigrate();
|
|||
|
|
|
|||
|
|
if (filesToMigrate.isEmpty()) {
|
|||
|
|
log.info("没有需要迁移的文件");
|
|||
|
|
return;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
log.info("找到 {} 个需要迁移的文件", filesToMigrate.size());
|
|||
|
|
|
|||
|
|
// 2. 分批迁移
|
|||
|
|
int totalBatches = (filesToMigrate.size() + batchSize - 1) / batchSize;
|
|||
|
|
|
|||
|
|
for (int i = 0; i < totalBatches; i++) {
|
|||
|
|
int start = i * batchSize;
|
|||
|
|
int end = Math.min(start + batchSize, filesToMigrate.size());
|
|||
|
|
List<FileMetadata> batch = filesToMigrate.subList(start, end);
|
|||
|
|
|
|||
|
|
log.info("处理第 {}/{} 批,文件数: {}", i + 1, totalBatches, batch.size());
|
|||
|
|
|
|||
|
|
// 并发迁移
|
|||
|
|
List<CompletableFuture<Boolean>> futures = batch.stream()
|
|||
|
|
.map(file -> CompletableFuture.supplyAsync(
|
|||
|
|
() -> migrateFile(file), executorService))
|
|||
|
|
.collect(Collectors.toList());
|
|||
|
|
|
|||
|
|
// 等待批次完成
|
|||
|
|
CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
|
|||
|
|
|
|||
|
|
long successCount = futures.stream()
|
|||
|
|
.map(CompletableFuture::join)
|
|||
|
|
.filter(result -> result)
|
|||
|
|
.count();
|
|||
|
|
|
|||
|
|
log.info("批次完成,成功: {}, 失败: {}",
|
|||
|
|
successCount, batch.size() - successCount);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
log.info("数据迁移任务完成");
|
|||
|
|
|
|||
|
|
} catch (Exception e) {
|
|||
|
|
log.error("数据迁移任务执行失败", e);
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 查询需要迁移的文件
|
|||
|
|
*/
|
|||
|
|
private List<FileMetadata> findFilesToMigrate() {
|
|||
|
|
Date cutoffDate = Date.from(Instant.now().minus(minDays, ChronoUnit.DAYS));
|
|||
|
|
|
|||
|
|
return metadataService.lambdaQuery()
|
|||
|
|
.eq(FileMetadata::getStorageType, "OSS")
|
|||
|
|
.eq(FileMetadata::getMigrationStatus, MigrationStatus.NOT_MIGRATED.getValue())
|
|||
|
|
.eq(FileMetadata::getIsDeleted, 0)
|
|||
|
|
.lt(FileMetadata::getCreateTime, cutoffDate)
|
|||
|
|
.last("LIMIT " + batchSize * 10) // 限制查询数量
|
|||
|
|
.list();
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 迁移单个文件
|
|||
|
|
*/
|
|||
|
|
@Override
|
|||
|
|
public boolean migrateFile(FileMetadata metadata) {
|
|||
|
|
String fileId = metadata.getFileId();
|
|||
|
|
|
|||
|
|
try {
|
|||
|
|
log.info("开始迁移文件: fileId={}, fileName={}",
|
|||
|
|
fileId, metadata.getFileName());
|
|||
|
|
|
|||
|
|
// 1. 更新迁移状态为迁移中
|
|||
|
|
metadata.setMigrationStatus(MigrationStatus.MIGRATING.getValue());
|
|||
|
|
metadataService.updateById(metadata);
|
|||
|
|
|
|||
|
|
// 2. 从OSS下载文件
|
|||
|
|
byte[] fileData = ossService.downloadFile(fileId);
|
|||
|
|
if (fileData == null || fileData.length == 0) {
|
|||
|
|
throw new RuntimeException("从OSS下载文件失败");
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 3. 上传到MinIO
|
|||
|
|
String minioUrl = minioService.uploadFile(fileId, fileData, metadata.getFileName());
|
|||
|
|
if (minioUrl == null) {
|
|||
|
|
throw new RuntimeException("上传到MinIO失败");
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 4. 更新CDN URL
|
|||
|
|
String newCdnUrl = convertMinioUrlToCdn(minioUrl);
|
|||
|
|
|
|||
|
|
// 5. 刷新旧的CDN缓存
|
|||
|
|
if (metadata.getCdnUrl() != null) {
|
|||
|
|
cdnService.refreshFiles(Arrays.asList(metadata.getCdnUrl()));
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 6. 删除OSS源文件(可选)
|
|||
|
|
if (deleteSource) {
|
|||
|
|
boolean deleted = ossService.deleteFile(fileId);
|
|||
|
|
if (!deleted) {
|
|||
|
|
log.warn("删除OSS源文件失败: fileId={}", fileId);
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 7. 更新元数据
|
|||
|
|
metadata.setStorageType("MINIO");
|
|||
|
|
metadata.setOriginalUrl(minioUrl);
|
|||
|
|
metadata.setCdnUrl(newCdnUrl);
|
|||
|
|
metadata.setMigrationStatus(MigrationStatus.MIGRATED.getValue());
|
|||
|
|
metadata.setMigrationTime(new Date());
|
|||
|
|
metadata.setUpdateTime(new Date());
|
|||
|
|
metadataService.updateById(metadata);
|
|||
|
|
|
|||
|
|
log.info("文件迁移成功: fileId={}", fileId);
|
|||
|
|
return true;
|
|||
|
|
|
|||
|
|
} catch (Exception e) {
|
|||
|
|
log.error("文件迁移失败: fileId=" + fileId, e);
|
|||
|
|
|
|||
|
|
// 更新迁移状态为失败
|
|||
|
|
metadata.setMigrationStatus(MigrationStatus.FAILED.getValue());
|
|||
|
|
metadata.setUpdateTime(new Date());
|
|||
|
|
metadataService.updateById(metadata);
|
|||
|
|
|
|||
|
|
return false;
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 转换MinIO URL为CDN URL
|
|||
|
|
*/
|
|||
|
|
private String convertMinioUrlToCdn(String minioUrl) {
|
|||
|
|
@Value("${cdn.minio.domain}")
|
|||
|
|
String minioCdnDomain;
|
|||
|
|
|
|||
|
|
@Value("${storage.minio.endpoint}")
|
|||
|
|
String minioEndpoint;
|
|||
|
|
|
|||
|
|
String cdnUrl = minioUrl.replace(minioEndpoint, minioCdnDomain);
|
|||
|
|
cdnUrl = cdnUrl.replaceAll(":\\d+", ""); // 移除端口号
|
|||
|
|
cdnUrl = cdnUrl.replace("http://", "https://"); // 使用HTTPS
|
|||
|
|
|
|||
|
|
return cdnUrl;
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
## 6. API接口
|
|||
|
|
|
|||
|
|
### 6.1 文件上传接口
|
|||
|
|
|
|||
|
|
```http
|
|||
|
|
POST /api-file/upload
|
|||
|
|
Content-Type: multipart/form-data
|
|||
|
|
|
|||
|
|
参数:
|
|||
|
|
- file: 文件内容
|
|||
|
|
- bizType: 业务类型(可选)
|
|||
|
|
|
|||
|
|
响应:
|
|||
|
|
{
|
|||
|
|
"code": 200,
|
|||
|
|
"message": "上传成功",
|
|||
|
|
"data": {
|
|||
|
|
"fileId": "abc123",
|
|||
|
|
"fileName": "test.jpg",
|
|||
|
|
"fileSize": 1024000,
|
|||
|
|
"cdnUrl": "https://oss-cdn.gofly.com/abc123.jpg",
|
|||
|
|
"storageType": "OSS"
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
### 6.2 获取文件URL接口
|
|||
|
|
|
|||
|
|
```http
|
|||
|
|
GET /api-file/url/{fileId}
|
|||
|
|
|
|||
|
|
响应:
|
|||
|
|
{
|
|||
|
|
"code": 200,
|
|||
|
|
"message": "success",
|
|||
|
|
"data": {
|
|||
|
|
"url": "https://oss-cdn.gofly.com/abc123.jpg",
|
|||
|
|
"type": "cdn"
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
### 6.3 批量获取文件URL接口
|
|||
|
|
|
|||
|
|
```http
|
|||
|
|
POST /api-file/urls
|
|||
|
|
Content-Type: application/json
|
|||
|
|
|
|||
|
|
{
|
|||
|
|
"fileIds": ["file1", "file2", "file3"]
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
响应:
|
|||
|
|
{
|
|||
|
|
"code": 200,
|
|||
|
|
"message": "success",
|
|||
|
|
"data": [
|
|||
|
|
{
|
|||
|
|
"fileId": "file1",
|
|||
|
|
"url": "https://oss-cdn.gofly.com/file1.jpg",
|
|||
|
|
"storageType": "OSS"
|
|||
|
|
},
|
|||
|
|
{
|
|||
|
|
"fileId": "file2",
|
|||
|
|
"url": "https://minio-cdn.gofly.com/file2.jpg",
|
|||
|
|
"storageType": "MINIO"
|
|||
|
|
}
|
|||
|
|
]
|
|||
|
|
}
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
### 6.4 手动迁移接口
|
|||
|
|
|
|||
|
|
```http
|
|||
|
|
POST /api-file/migrate/{fileId}
|
|||
|
|
|
|||
|
|
响应:
|
|||
|
|
{
|
|||
|
|
"code": 200,
|
|||
|
|
"message": "迁移任务已提交",
|
|||
|
|
"data": {
|
|||
|
|
"taskId": "task123",
|
|||
|
|
"status": "processing"
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
### 6.5 查询迁移状态接口
|
|||
|
|
|
|||
|
|
```http
|
|||
|
|
GET /api-file/migrate/status
|
|||
|
|
|
|||
|
|
响应:
|
|||
|
|
{
|
|||
|
|
"code": 200,
|
|||
|
|
"message": "success",
|
|||
|
|
"data": {
|
|||
|
|
"total": 10000,
|
|||
|
|
"migrated": 8500,
|
|||
|
|
"failed": 100,
|
|||
|
|
"pending": 1400,
|
|||
|
|
"lastMigrationTime": "2024-01-15 02:00:00"
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
## 7. 数据迁移
|
|||
|
|
|
|||
|
|
### 7.1 迁移策略
|
|||
|
|
|
|||
|
|
1. **自动迁移**: 每天凌晨2点自动执行
|
|||
|
|
2. **手动迁移**: 通过管理接口手动触发
|
|||
|
|
3. **批量迁移**: 支持批量并发迁移
|
|||
|
|
4. **失败重试**: 自动重试失败的迁移任务
|
|||
|
|
|
|||
|
|
### 7.2 迁移流程
|
|||
|
|
|
|||
|
|
```mermaid
|
|||
|
|
sequenceDiagram
|
|||
|
|
participant S as 调度器
|
|||
|
|
participant M as 迁移服务
|
|||
|
|
participant O as OSS
|
|||
|
|
participant Mi as MinIO
|
|||
|
|
participant C as CDN
|
|||
|
|
participant DB as 数据库
|
|||
|
|
|
|||
|
|
S->>M: 触发迁移任务
|
|||
|
|
M->>DB: 查询需要迁移的文件
|
|||
|
|
DB-->>M: 返回文件列表
|
|||
|
|
|
|||
|
|
loop 每个文件
|
|||
|
|
M->>DB: 更新状态为迁移中
|
|||
|
|
M->>O: 下载文件
|
|||
|
|
O-->>M: 返回文件数据
|
|||
|
|
M->>Mi: 上传文件
|
|||
|
|
Mi-->>M: 返回新URL
|
|||
|
|
M->>C: 刷新CDN缓存
|
|||
|
|
M->>O: 删除源文件(可选)
|
|||
|
|
M->>DB: 更新元数据
|
|||
|
|
end
|
|||
|
|
|
|||
|
|
M-->>S: 迁移完成
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
### 7.3 迁移监控
|
|||
|
|
|
|||
|
|
```java
|
|||
|
|
@Component
|
|||
|
|
public class MigrationMonitor {
|
|||
|
|
|
|||
|
|
@Autowired
|
|||
|
|
private MeterRegistry meterRegistry;
|
|||
|
|
|
|||
|
|
public void recordMigration(boolean success, long duration) {
|
|||
|
|
// 记录迁移指标
|
|||
|
|
meterRegistry.counter("file.migration.total",
|
|||
|
|
"status", success ? "success" : "failed").increment();
|
|||
|
|
|
|||
|
|
meterRegistry.timer("file.migration.duration")
|
|||
|
|
.record(duration, TimeUnit.MILLISECONDS);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
@Scheduled(fixedRate = 60000)
|
|||
|
|
public void reportStatus() {
|
|||
|
|
// 定期报告迁移状态
|
|||
|
|
MigrationStats stats = getMigrationStats();
|
|||
|
|
log.info("迁移统计 - 总数: {}, 成功: {}, 失败: {}, 待处理: {}",
|
|||
|
|
stats.getTotal(), stats.getSuccess(),
|
|||
|
|
stats.getFailed(), stats.getPending());
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
## 8. 监控运维
|
|||
|
|
|
|||
|
|
### 8.1 关键指标监控(基于TimeWindowStorageService日志)
|
|||
|
|
|
|||
|
|
| 指标名称 | 说明 | 告警阈值 | 日志关键字 |
|
|||
|
|
|---------|------|---------|-----------|
|
|||
|
|
| `storage.route.decision` | 路由决策统计 | - | `时间窗口判定` |
|
|||
|
|
| `storage.oss.query` | OSS查询成功率 | <95% | `OSS查询成功/失败` |
|
|||
|
|
| `storage.s3.query` | S3查询成功率 | <95% | `S3查询成功/失败` |
|
|||
|
|
| `storage.fallback.count` | 降级次数 | >100/小时 | `降级到OSS/S3` |
|
|||
|
|
| `api.response.time` | API响应时间 | >3秒 | - |
|
|||
|
|
| `storage.error.rate` | 存储错误率 | >1% | `查询异常` |
|
|||
|
|
|
|||
|
|
### 8.2 日志分析(基于实际实现)
|
|||
|
|
|
|||
|
|
```java
|
|||
|
|
// 路由决策日志
|
|||
|
|
log.info("时间窗口判定: fileId={} createTime={} hotDataDays={} enableTimeWindow={} -> storageType={}",
|
|||
|
|
fileInfo.getId(), fileInfo.getCreateTime(), hotDataDays, enableTimeWindow, storageType);
|
|||
|
|
|
|||
|
|
// 查询成功日志
|
|||
|
|
log.info("OSS查询成功: fileId={}, url={}", fileInfo.getId(), ossUrl);
|
|||
|
|
log.info("S3查询成功: fileId={}, url={}", fileInfo.getId(), s3Url);
|
|||
|
|
|
|||
|
|
// 降级日志
|
|||
|
|
log.warn("S3查询失败,降级到OSS: fileId={}", fileInfo.getId());
|
|||
|
|
log.warn("OSS查询失败,降级到S3: fileId={}", fileInfo.getId());
|
|||
|
|
|
|||
|
|
// 异常日志
|
|||
|
|
log.error("智能存储查询失败: fileId={}, error={}", fileId, e.getMessage(), e);
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
### 8.3 监控大盘配置
|
|||
|
|
|
|||
|
|
```yaml
|
|||
|
|
# Prometheus监控配置
|
|||
|
|
metrics:
|
|||
|
|
storage:
|
|||
|
|
route:
|
|||
|
|
hot_data_count: # 热数据路由次数
|
|||
|
|
labels: [service, storage_type]
|
|||
|
|
cold_data_count: # 冷数据路由次数
|
|||
|
|
labels: [service, storage_type]
|
|||
|
|
query:
|
|||
|
|
success_rate: # 查询成功率
|
|||
|
|
labels: [storage_type]
|
|||
|
|
fallback_count: # 降级次数
|
|||
|
|
labels: [from, to]
|
|||
|
|
performance:
|
|||
|
|
response_time: # 响应时间
|
|||
|
|
labels: [method, storage_type]
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
### 8.3 健康检查
|
|||
|
|
|
|||
|
|
```java
|
|||
|
|
@RestController
|
|||
|
|
@RequestMapping("/health")
|
|||
|
|
public class HealthController {
|
|||
|
|
|
|||
|
|
@GetMapping("/storage")
|
|||
|
|
public Result checkStorage() {
|
|||
|
|
Map<String, Object> health = new HashMap<>();
|
|||
|
|
|
|||
|
|
// 检查OSS连接
|
|||
|
|
health.put("oss", checkOssConnection());
|
|||
|
|
|
|||
|
|
// 检查MinIO连接
|
|||
|
|
health.put("minio", checkMinioConnection());
|
|||
|
|
|
|||
|
|
// 检查CDN状态
|
|||
|
|
health.put("cdn", checkCdnStatus());
|
|||
|
|
|
|||
|
|
// 检查数据库连接
|
|||
|
|
health.put("database", checkDatabaseConnection());
|
|||
|
|
|
|||
|
|
return Result.succeed(health);
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
## 9. 故障处理
|
|||
|
|
|
|||
|
|
### 9.1 故障场景及处理(基于实际降级策略)
|
|||
|
|
|
|||
|
|
| 故障场景 | 影响 | TimeWindowStorageService处理方案 | 日志标识 |
|
|||
|
|
|---------|------|----------------------------------|----------|
|
|||
|
|
| OSS不可用 | 热数据无法访问 | 自动降级到S3查询 | `OSS查询失败,降级到S3` |
|
|||
|
|
| S3/MinIO不可用 | 冷数据无法访问 | 自动降级到OSS查询 | `S3查询失败,降级到OSS` |
|
|||
|
|
| 数据库连接失败 | 无元数据 | 按冷优先策略(S3→OSS) | `数据库未找到文件信息` |
|
|||
|
|
| CDN故障 | 访问变慢 | 返回源站直连URL | - |
|
|||
|
|
| 路径格式错误 | 查询失败 | 自动处理OSS域名前缀 | `去掉域名前缀转为相对路径` |
|
|||
|
|
|
|||
|
|
### 9.2 降级策略
|
|||
|
|
|
|||
|
|
```java
|
|||
|
|
@Component
|
|||
|
|
public class StorageFallback {
|
|||
|
|
|
|||
|
|
@HystrixCommand(fallbackMethod = "fallbackGetUrl")
|
|||
|
|
public String getFileUrl(String fileId) {
|
|||
|
|
// 正常逻辑
|
|||
|
|
return primaryStorage.getUrl(fileId);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
public String fallbackGetUrl(String fileId) {
|
|||
|
|
// 降级逻辑
|
|||
|
|
log.warn("存储服务降级: fileId={}", fileId);
|
|||
|
|
|
|||
|
|
// 1. 尝试从缓存获取
|
|||
|
|
String cachedUrl = cache.get(fileId);
|
|||
|
|
if (cachedUrl != null) {
|
|||
|
|
return cachedUrl;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 2. 尝试从备份存储获取
|
|||
|
|
return backupStorage.getUrl(fileId);
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
### 9.3 容灾方案
|
|||
|
|
|
|||
|
|
1. **多地域部署**: OSS和MinIO都采用多地域部署
|
|||
|
|
2. **数据备份**: 重要数据定期备份
|
|||
|
|
3. **服务冗余**: 关键服务多实例部署
|
|||
|
|
4. **自动切换**: 检测到故障自动切换到备用服务
|
|||
|
|
|
|||
|
|
## 10. 性能优化
|
|||
|
|
|
|||
|
|
### 10.1 查询优化策略
|
|||
|
|
|
|||
|
|
#### 10.1.1 数据库查询优化
|
|||
|
|
```java
|
|||
|
|
private FileInfo getFileInfoByPath(String filePath) {
|
|||
|
|
// 1. 先按path字段查询(主要路径)
|
|||
|
|
QueryWrapper<FileInfo> wrapper = new QueryWrapper<>();
|
|||
|
|
wrapper.eq("path", filePath).last("limit 1");
|
|||
|
|
FileInfo info = fileMapper.selectOne(wrapper);
|
|||
|
|
|
|||
|
|
// 2. 兼容历史数据(name字段)
|
|||
|
|
if (info == null) {
|
|||
|
|
wrapper = new QueryWrapper<>();
|
|||
|
|
wrapper.eq("name", filePath).last("limit 1");
|
|||
|
|
info = fileMapper.selectOne(wrapper);
|
|||
|
|
}
|
|||
|
|
return info;
|
|||
|
|
}
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
#### 10.1.2 路径标准化处理
|
|||
|
|
```java
|
|||
|
|
// 处理OSS完整URL,转为相对路径
|
|||
|
|
final String OSS_DOMAIN_PREFIX = "https://goflyapp.oss-cn-beijing.aliyuncs.com/";
|
|||
|
|
String normalized = path.startsWith(OSS_DOMAIN_PREFIX)
|
|||
|
|
? path.substring(OSS_DOMAIN_PREFIX.length())
|
|||
|
|
: path;
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
### 10.2 缓存优化
|
|||
|
|
|
|||
|
|
```java
|
|||
|
|
@Configuration
|
|||
|
|
public class CacheConfig {
|
|||
|
|
|
|||
|
|
@Bean
|
|||
|
|
public CacheManager cacheManager() {
|
|||
|
|
SimpleCacheManager cacheManager = new SimpleCacheManager();
|
|||
|
|
|
|||
|
|
// 文件URL缓存(1小时)
|
|||
|
|
Cache urlCache = new CaffeineCache("fileUrls",
|
|||
|
|
Caffeine.newBuilder()
|
|||
|
|
.expireAfterWrite(1, TimeUnit.HOURS)
|
|||
|
|
.maximumSize(10000)
|
|||
|
|
.build());
|
|||
|
|
|
|||
|
|
// 元数据缓存(10分钟)
|
|||
|
|
Cache metadataCache = new CaffeineCache("metadata",
|
|||
|
|
Caffeine.newBuilder()
|
|||
|
|
.expireAfterWrite(10, TimeUnit.MINUTES)
|
|||
|
|
.maximumSize(5000)
|
|||
|
|
.build());
|
|||
|
|
|
|||
|
|
cacheManager.setCaches(Arrays.asList(urlCache, metadataCache));
|
|||
|
|
return cacheManager;
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
### 10.2 并发优化
|
|||
|
|
|
|||
|
|
```java
|
|||
|
|
@Configuration
|
|||
|
|
public class ThreadPoolConfig {
|
|||
|
|
|
|||
|
|
@Bean("fileProcessExecutor")
|
|||
|
|
public ExecutorService fileProcessExecutor() {
|
|||
|
|
return new ThreadPoolExecutor(
|
|||
|
|
10, // 核心线程数
|
|||
|
|
50, // 最大线程数
|
|||
|
|
60L, // 空闲时间
|
|||
|
|
TimeUnit.SECONDS,
|
|||
|
|
new LinkedBlockingQueue<>(1000),
|
|||
|
|
new ThreadFactory() {
|
|||
|
|
private final AtomicInteger counter = new AtomicInteger();
|
|||
|
|
|
|||
|
|
@Override
|
|||
|
|
public Thread newThread(Runnable r) {
|
|||
|
|
Thread thread = new Thread(r);
|
|||
|
|
thread.setName("file-process-" + counter.incrementAndGet());
|
|||
|
|
return thread;
|
|||
|
|
}
|
|||
|
|
},
|
|||
|
|
new ThreadPoolExecutor.CallerRunsPolicy()
|
|||
|
|
);
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
### 10.3 批量处理优化
|
|||
|
|
|
|||
|
|
```java
|
|||
|
|
@Service
|
|||
|
|
public class BatchProcessService {
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* 批量获取文件URL(优化版)
|
|||
|
|
*/
|
|||
|
|
public Map<String, String> batchGetUrls(List<String> fileIds) {
|
|||
|
|
// 1. 先从缓存批量获取
|
|||
|
|
Map<String, String> cachedUrls = batchGetFromCache(fileIds);
|
|||
|
|
|
|||
|
|
// 2. 找出未命中的
|
|||
|
|
List<String> uncachedIds = fileIds.stream()
|
|||
|
|
.filter(id -> !cachedUrls.containsKey(id))
|
|||
|
|
.collect(Collectors.toList());
|
|||
|
|
|
|||
|
|
if (uncachedIds.isEmpty()) {
|
|||
|
|
return cachedUrls;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 3. 批量查询数据库
|
|||
|
|
Map<String, FileMetadata> metadataMap = metadataService
|
|||
|
|
.lambdaQuery()
|
|||
|
|
.in(FileMetadata::getFileId, uncachedIds)
|
|||
|
|
.list()
|
|||
|
|
.stream()
|
|||
|
|
.collect(Collectors.toMap(
|
|||
|
|
FileMetadata::getFileId,
|
|||
|
|
Function.identity()
|
|||
|
|
));
|
|||
|
|
|
|||
|
|
// 4. 生成URL并缓存
|
|||
|
|
Map<String, String> newUrls = new HashMap<>();
|
|||
|
|
for (FileMetadata metadata : metadataMap.values()) {
|
|||
|
|
String url = generateUrl(metadata);
|
|||
|
|
newUrls.put(metadata.getFileId(), url);
|
|||
|
|
cacheUrl(metadata.getFileId(), url);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 5. 合并结果
|
|||
|
|
cachedUrls.putAll(newUrls);
|
|||
|
|
return cachedUrls;
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
## 附录
|
|||
|
|
|
|||
|
|
### A. 常见问题FAQ
|
|||
|
|
|
|||
|
|
**Q1: 为什么选择90天作为时间窗口?**
|
|||
|
|
A: 根据业务分析,90天内的文件访问频率占总访问量的80%以上,90天后访问量显著下降。可通过配置`zlt.storage.time-router.days`调整。
|
|||
|
|
|
|||
|
|
**Q2: 文件查询失败如何处理?**
|
|||
|
|
A: TimeWindowStorageService实现了自动降级策略:
|
|||
|
|
- 热数据(OSS)查询失败自动降级到S3
|
|||
|
|
- 冷数据(S3)查询失败自动降级到OSS
|
|||
|
|
- 确保文件始终可访问
|
|||
|
|
|
|||
|
|
**Q3: 如何处理无元数据的文件?**
|
|||
|
|
A: `getSmartViewUrlByPath`方法支持无元数据场景:
|
|||
|
|
- 时间窗口关闭:直接查询OSS
|
|||
|
|
- 时间窗口开启:按冷优先策略(先S3后OSS)
|
|||
|
|
|
|||
|
|
**Q4: CDN配置如何生效?**
|
|||
|
|
A: 在`applyCdnAcceleration`方法中自动将存储URL转换为CDN URL,需要配置:
|
|||
|
|
- `cdn.oss.domain`: OSS CDN域名
|
|||
|
|
- `cdn.s3.domain`: S3/MinIO CDN域名
|
|||
|
|
|
|||
|
|
**Q5: 如何监控系统运行状态?**
|
|||
|
|
A: 通过日志关键字监控:
|
|||
|
|
- `时间窗口判定`: 路由决策
|
|||
|
|
- `OSS/S3查询成功/失败`: 查询状态
|
|||
|
|
- `降级到OSS/S3`: 降级事件
|
|||
|
|
|
|||
|
|
### B. 性能测试结果
|
|||
|
|
|
|||
|
|
| 测试场景 | 并发数 | 平均响应时间 | 吞吐量 | 优化效果 |
|
|||
|
|
|---------|--------|-------------|--------|----------|
|
|||
|
|
| getSmartViewUrl | 100 | 15ms | 6000/s | 基线 |
|
|||
|
|
| getSmartViewUrlByPath | 100 | 20ms | 5000/s | 路径查询 |
|
|||
|
|
| 热数据(OSS+CDN) | 500 | 30ms | 15000/s | 3倍提升 |
|
|||
|
|
| 冷数据(S3+CDN) | 500 | 50ms | 10000/s | 2倍提升 |
|
|||
|
|
| 降级场景 | 100 | 100ms | 1000/s | 保障可用 |
|
|||
|
|
|
|||
|
|
### C. 成本效益分析
|
|||
|
|
|
|||
|
|
| 指标 | 优化前 | 优化后 | 节省 |
|
|||
|
|
|------|--------|--------|------|
|
|||
|
|
| **存储成本** | | | |
|
|||
|
|
| OSS存储(全量) | ¥10000/月 | ¥3000/月 | 70% |
|
|||
|
|
| MinIO存储 | ¥0 | ¥1000/月 | - |
|
|||
|
|
| **流量成本** | | | |
|
|||
|
|
| OSS流量 | ¥5000/月 | ¥2000/月 | 60% |
|
|||
|
|
| CDN流量 | ¥2000/月 | ¥3000/月 | -50% |
|
|||
|
|
| **总成本** | ¥17000/月 | ¥9000/月 | 47% |
|
|||
|
|
| **性能提升** | | | |
|
|||
|
|
| 平均响应时间 | 200ms | 50ms | 75% |
|
|||
|
|
| CDN命中率 | 60% | 85% | 42% |
|
|||
|
|
|
|||
|
|
### D. 实施建议
|
|||
|
|
|
|||
|
|
1. **阶段一:评估现状**(1周)
|
|||
|
|
- 分析文件访问模式
|
|||
|
|
- 确定时间窗口阈值
|
|||
|
|
- 评估存储成本
|
|||
|
|
|
|||
|
|
2. **阶段二:部署TimeWindowStorageService**(2周)
|
|||
|
|
- 配置双存储环境
|
|||
|
|
- 部署时间窗口服务
|
|||
|
|
- 集成CDN加速
|
|||
|
|
|
|||
|
|
3. **阶段三:数据迁移**(4周)
|
|||
|
|
- 制定迁移计划
|
|||
|
|
- 批量迁移历史数据
|
|||
|
|
- 验证数据完整性
|
|||
|
|
|
|||
|
|
4. **阶段四:监控优化**(持续)
|
|||
|
|
- 部署监控系统
|
|||
|
|
- 优化路由策略
|
|||
|
|
- 调整时间窗口
|
|||
|
|
|
|||
|
|
---
|
|||
|
|
|
|||
|
|
## 总结
|
|||
|
|
|
|||
|
|
本方案通过结合**TimeWindowStorageService**的智能路由能力和CDN加速技术,实现了:
|
|||
|
|
|
|||
|
|
✅ **成本优化**:存储成本降低47%,合理利用冷热存储特性
|
|||
|
|
✅ **性能提升**:响应时间减少75%,CDN命中率提升至85%
|
|||
|
|
✅ **高可用性**:自动降级策略,确保服务始终可用
|
|||
|
|
✅ **易于维护**:统一的服务接口,透明的存储切换
|
|||
|
|
✅ **灵活扩展**:可配置的时间窗口,支持多种存储后端
|
|||
|
|
|
|||
|
|
## 更新日志
|
|||
|
|
|
|||
|
|
- 2024-01-20: 初始版本
|
|||
|
|
- 2024-01-25: 集成TimeWindowStorageService
|
|||
|
|
- 2024-01-30: 优化降级策略和CDN配置
|
|||
|
|
- 2024-02-05: 完善监控和性能优化方案
|
|||
|
|
|
|||
|
|
## 联系方式
|
|||
|
|
|
|||
|
|
- 技术支持: tech@gofly.com
|
|||
|
|
- 文档维护: file-center@gofly.com
|