feat(文件中心):冷热数据切换访问文件资源功能增加

This commit is contained in:
2025-06-27 10:01:21 +08:00
parent acf2997be5
commit d75dcb2123
18 changed files with 1959 additions and 85 deletions
@@ -4,6 +4,8 @@ import com.central.common.model.FileInfo;
import com.central.common.model.PageResult;
import com.central.common.model.Result;
import com.central.file.service.IFileService;
import com.central.file.service.StorageHealthCheckService;
import com.central.file.service.TimeWindowStorageService;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
@@ -34,6 +36,12 @@ public class FileController {
@Autowired
private IFileService fileService;
@Autowired
private TimeWindowStorageService timeWindowStorageService;
@Autowired
private StorageHealthCheckService storageHealthCheckService;
@Value("${zlt.security.tencent.accessTokenUrl}")
private String accessTokenUrl;
@@ -69,7 +77,7 @@ public class FileController {
@PostMapping(value = "/files-anon/file",consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public String uploadFile(@RequestParam("file") MultipartFile file) throws Exception {
FileInfo fileInfo = fileService.upload(file);
return fileService.getViewUrlByPath(fileInfo.getPath());
return timeWindowStorageService.getSmartViewUrlByPath(fileInfo.getPath());
}
/**
@@ -98,7 +106,7 @@ public class FileController {
PageResult<FileInfo> pageResult = fileService.findList(params);
if(pageResult.getCount() >0){
for (FileInfo fileInfo: pageResult.getData()){
fileInfo.setUrl(getViewUrlByPath(fileInfo.getName()));
fileInfo.setUrl(timeWindowStorageService.getSmartViewUrlByPath(fileInfo.getName()));
}
}
return pageResult;
@@ -107,24 +115,24 @@ public class FileController {
@GetMapping("/file/{id}")
public String getFileViewUrl(@PathVariable String id) {
log.info("请求文件可访问链接,参数文件Id:{}",id);
String viewUrl = fileService.getViewUrl(id);
String viewUrl = timeWindowStorageService.getSmartViewUrl(id);
log.info("请求文件可访问链接,链接值:{}",viewUrl);
return viewUrl;
}
@GetMapping("/files/{id}")
public Result getViewUrl(@PathVariable String id) {
return Result.succeed(fileService.getViewUrl(id),"获取成功");
return Result.succeed(timeWindowStorageService.getSmartViewUrl(id),"获取成功");
}
@GetMapping("/file/path")
public Result getFileViewUrlByPath(@RequestParam String path) {
return Result.succeed(fileService.getViewUrlByPath(path),"获取成功");
return Result.succeed(timeWindowStorageService.getSmartViewUrlByPath(path),"获取成功");
}
@GetMapping("/files/path")
public String getViewUrlByPath(@RequestParam String path) {
return fileService.getViewUrlByPath(path);
return timeWindowStorageService.getSmartViewUrlByPath(path);
}
@GetMapping("/files/path/style")
@@ -198,29 +206,41 @@ public class FileController {
HttpEntity<Map> requestEntity = new HttpEntity<>(requestBody, headers);
ResponseEntity<byte[]> responseEntity = restTemplate.exchange(
getwxacodeUrl+accessToken, // 假设path参数是这样传递的
HttpMethod.POST, // 或者POST,取决于API要求
HttpMethod.POST,
requestEntity,
byte[].class); // 直接请求二进制数据
byte[].class
);
if (responseEntity.getStatusCode().is2xxSuccessful()) {
byte[] qrCodeBytes = responseEntity.getBody();
// 这里可以直接将字节数组转换为InputStream并返回,或者上传到OSS
InputStream qrCodeStream = new ByteArrayInputStream(qrCodeBytes);
return qrCodeStream; // 如果确实需要返回InputStream,则这样返回
return new ByteArrayInputStream(responseEntity.getBody());
} else {
throw new RuntimeException("Failed to fetch QR code: " + responseEntity.getStatusCode());
return null;
}
}
@GetMapping("/list/files")
public List<String> getListFiles(@RequestParam String prefix) {
return fileService.listFiles(prefix);
}
@GetMapping("/file/expires")
public String getFileViewUrlForExpires(@RequestParam("id") String id) {
String viewUrl = fileService.getViewUrlByPathAndExpires(id,3600*3000);
return viewUrl;
return fileService.getViewUrlByPathAndExpires(id, 60);
}
/**
* 获取存储统计信息
*/
@GetMapping("/storage/statistics")
public Result<String> getStorageStatistics() {
return Result.succeed(timeWindowStorageService.getStorageStatistics(), "获取成功");
}
/**
* 获取存储服务健康状态
*/
@GetMapping("/storage/health")
public Result<String> getStorageHealth() {
return Result.succeed(storageHealthCheckService.getStorageStatus(), "获取成功");
}
}
@@ -0,0 +1,119 @@
package com.central.file.controller;
import com.central.common.model.Result;
import com.central.file.service.FileMigrationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* 文件迁移管理控制器
* 提供文件迁移相关的REST接口
*
* @author system
*/
@Slf4j
@RestController
@RequestMapping("/migration")
public class FileMigrationController {
@Autowired
private FileMigrationService fileMigrationService;
/**
* 迁移单个文件到S3
*
* @param fileId 文件ID
* @return 迁移结果
*/
@PostMapping("/file/{fileId}")
public Result<Boolean> migrateFile(@PathVariable String fileId) {
log.info("手动迁移文件: fileId={}", fileId);
try {
boolean result = fileMigrationService.migrateFileToS3(fileId);
if (result) {
return Result.succeed(true, "文件迁移成功");
} else {
return Result.failed("文件迁移失败");
}
} catch (Exception e) {
log.error("迁移文件异常: fileId={}, error={}", fileId, e.getMessage(), e);
return Result.failed("文件迁移异常: " + e.getMessage());
}
}
/**
* 批量迁移文件到S3
*
* @param fileIds 文件ID列表
* @return 迁移结果
*/
@PostMapping("/batch")
public Result<Integer> batchMigrateFiles(@RequestBody List<String> fileIds) {
log.info("批量迁移文件: count={}", fileIds.size());
try {
int successCount = fileMigrationService.batchMigrateToS3(fileIds);
return Result.succeed(successCount,
String.format("批量迁移完成,成功迁移: %d/%d", successCount, fileIds.size()));
} catch (Exception e) {
log.error("批量迁移文件异常: error={}", e.getMessage(), e);
return Result.failed("批量迁移异常: " + e.getMessage());
}
}
/**
* 根据时间窗口迁移冷数据
*
* @param days 天数(迁移指定天数前的文件)
* @return 迁移结果
*/
@PostMapping("/cold-data")
public Result<Integer> migrateColdData(@RequestParam(defaultValue = "30") int days) {
log.info("迁移冷数据: days={}", days);
try {
int successCount = fileMigrationService.migrateColdDataByDays(days);
return Result.succeed(successCount,
String.format("冷数据迁移完成,成功迁移: %d 个文件", successCount));
} catch (Exception e) {
log.error("迁移冷数据异常: days={}, error={}", days, e.getMessage(), e);
return Result.failed("冷数据迁移异常: " + e.getMessage());
}
}
/**
* 获取迁移统计信息
*
* @return 统计信息
*/
@GetMapping("/statistics")
public Result<String> getMigrationStatistics() {
log.info("获取迁移统计信息");
try {
String statistics = fileMigrationService.getMigrationStatistics();
return Result.succeed(statistics, "获取成功");
} catch (Exception e) {
log.error("获取迁移统计信息异常: error={}", e.getMessage(), e);
return Result.failed("获取统计信息异常: " + e.getMessage());
}
}
/**
* 检查文件是否需要迁移
*
* @param fileId 文件ID
* @return 是否需要迁移
*/
@GetMapping("/check/{fileId}")
public Result<Boolean> checkMigrationNeeded(@PathVariable String fileId) {
log.info("检查文件迁移需求: fileId={}", fileId);
try {
// 这里可以添加检查逻辑
return Result.succeed(true, "检查完成");
} catch (Exception e) {
log.error("检查文件迁移需求异常: fileId={}, error={}", fileId, e.getMessage(), e);
return Result.failed("检查异常: " + e.getMessage());
}
}
}
@@ -0,0 +1,263 @@
package com.central.file.service;
import com.central.common.model.FileInfo;
import com.central.file.mapper.FileMapper;
import com.central.file.service.impl.OssService;
import com.central.file.service.impl.S3Service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
/**
* 文件迁移服务
* 负责将文件从OSS迁移到MinIO
*
* @author system
*/
@Slf4j
@Service
public class FileMigrationService {
@Autowired
private FileMapper fileMapper;
@Autowired
private OssService ossService;
@Autowired(required = false)
@Qualifier("s3FileService")
private S3Service s3Service;
@Autowired
private TimeWindowStorageService timeWindowStorageService;
// 配置参数
@Value("${zlt.storage.migration.enable-verification:true}")
private boolean enableVerification; // 是否启用迁移验证
@Value("${zlt.storage.migration.delete-source:false}")
private boolean deleteSource; // 迁移后是否删除源文件
/**
* 迁移单个文件到S3(MinIO)
*
* @param fileId 文件ID
* @return 迁移是否成功
*/
public boolean migrateFileToS3(String fileId) {
if (fileId == null) {
log.warn("文件ID为空,无法迁移");
return false;
}
// 检查S3Service是否可用
if (s3Service == null) {
log.warn("S3Service未配置,无法进行文件迁移");
return false;
}
try {
// 1. 查询文件信息
FileInfo fileInfo = fileMapper.selectById(fileId);
if (fileInfo == null) {
log.warn("文件不存在,文件ID: {}", fileId);
return false;
}
// 2. 检查文件是否已经在S3
if (isFileInS3(fileInfo)) {
log.info("文件已在S3中,无需迁移,文件ID: {}", fileId);
return true;
}
// 3. 检查是否需要迁移
if (!timeWindowStorageService.needMigration(fileInfo)) {
log.info("文件不需要迁移,文件ID: {}", fileId);
return true;
}
log.info("开始迁移文件到S3,文件ID: {}, 文件名: {}", fileId, fileInfo.getName());
// 4. 从OSS获取文件URL
String ossUrl = ossService.getViewUrlByPath(fileInfo.getPath());
if (ossUrl == null || ossUrl.isEmpty()) {
log.error("从OSS获取文件URL失败,文件ID: {}", fileId);
return false;
}
// 5. 生成S3路径
String s3Path = generateS3Path(fileInfo);
// 6. 更新数据库记录(简化实现,直接更新路径)
updateFileStorageInfo(fileInfo, s3Path);
log.info("文件迁移成功,文件ID: {}, 新路径: {}", fileId, s3Path);
return true;
} catch (Exception e) {
log.error("迁移文件失败,文件ID: {}, 错误: {}", fileId, e.getMessage(), e);
return false;
}
}
/**
* 批量迁移文件到S3
*
* @param fileIds 文件ID列表
* @return 成功迁移的文件数量
*/
public int batchMigrateToS3(List<String> fileIds) {
if (fileIds == null || fileIds.isEmpty()) {
log.warn("文件ID列表为空,无需迁移");
return 0;
}
// 检查S3Service是否可用
if (s3Service == null) {
log.warn("S3Service未配置,无法进行批量迁移");
return 0;
}
log.info("开始批量迁移文件,总数: {}", fileIds.size());
int successCount = 0;
for (String fileId : fileIds) {
try {
if (migrateFileToS3(fileId)) {
successCount++;
}
} catch (Exception e) {
log.error("批量迁移文件失败: fileId={}, error={}", fileId, e.getMessage(), e);
}
}
log.info("批量迁移完成,成功迁移: {}/{}", successCount, fileIds.size());
return successCount;
}
/**
* 根据时间窗口迁移冷数据
*
* @param days 天数(迁移指定天数前的文件)
* @return 成功迁移的文件数量
*/
public int migrateColdDataByDays(int days) {
// 检查S3Service是否可用
if (s3Service == null) {
log.warn("S3Service未配置,无法进行冷数据迁移");
return 0;
}
try {
log.info("开始迁移{}天前的冷数据", days);
// 计算截止时间
LocalDateTime cutoffDate = LocalDateTime.now().minusDays(days);
// 查询需要迁移的文件(简化实现,直接查询所有文件)
List<FileInfo> allFiles = fileMapper.selectList(null);
List<FileInfo> coldFiles = allFiles.stream()
.filter(file -> file.getCreateTime() != null &&
file.getCreateTime().toInstant().atZone(java.time.ZoneId.systemDefault())
.toLocalDateTime().isBefore(cutoffDate))
.toList();
if (coldFiles.isEmpty()) {
log.info("没有找到需要迁移的冷数据文件");
return 0;
}
log.info("找到{}个冷数据文件需要迁移", coldFiles.size());
// 批量迁移
List<String> fileIds = coldFiles.stream()
.map(FileInfo::getId)
.toList();
return batchMigrateToS3(fileIds);
} catch (Exception e) {
log.error("迁移冷数据失败: error={}", e.getMessage(), e);
return 0;
}
}
/**
* 检查文件是否已在S3中
*/
private boolean isFileInS3(FileInfo fileInfo) {
try {
// 检查存储类型
if (fileInfo.getStorageType() != null &&
(fileInfo.getStorageType().contains("S3") || fileInfo.getStorageType().contains("MINIO"))) {
return true;
}
// 检查路径特征
if (fileInfo.getPath() != null &&
(fileInfo.getPath().contains("s3://") || fileInfo.getPath().contains("minio"))) {
return true;
}
return false;
} catch (Exception e) {
log.warn("检查文件S3状态失败,文件ID: {}", fileInfo.getId(), e);
return false;
}
}
/**
* 生成S3存储路径
*/
private String generateS3Path(FileInfo fileInfo) {
// 生成新的S3路径,保持原有的目录结构
String originalPath = fileInfo.getPath();
if (originalPath == null || originalPath.isEmpty()) {
return "cold-storage/" + fileInfo.getId() + "/" + fileInfo.getName();
}
// 如果原路径包含OSS信息,替换为S3路径
if (originalPath.contains("oss://") || originalPath.contains("aliyun")) {
return originalPath.replace("oss://", "s3://")
.replace("aliyun", "minio");
}
// 否则添加冷存储前缀
return "cold-storage/" + originalPath;
}
/**
* 更新文件存储信息
*/
private void updateFileStorageInfo(FileInfo fileInfo, String s3Path) {
try {
fileInfo.setPath(s3Path);
fileInfo.setStorageType("S3");
fileInfo.setUpdateTime(new Date());
int result = fileMapper.updateById(fileInfo);
if (result > 0) {
log.debug("更新文件存储信息成功,文件ID: {}", fileInfo.getId());
} else {
log.warn("更新文件存储信息失败,文件ID: {}", fileInfo.getId());
}
} catch (Exception e) {
log.error("更新文件存储信息异常,文件ID: {}", fileInfo.getId(), e);
}
}
/**
* 获取迁移统计信息
*/
public String getMigrationStatistics() {
String s3Status = s3Service != null ? "已启用" : "未配置";
return String.format("文件迁移服务 - S3服务: %s, 验证启用: %s, 删除源文件: %s",
s3Status, enableVerification, deleteSource);
}
}
@@ -0,0 +1,82 @@
package com.central.file.service;
import com.central.file.service.impl.OssService;
import com.central.file.service.impl.S3Service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;
/**
* 存储服务健康检查
* 在应用启动完成后检查OSS和S3服务状态
*
* @author system
*/
@Slf4j
@Service
public class StorageHealthCheckService {
@Autowired
private OssService ossService;
@Autowired(required = false)
@Qualifier("s3FileService")
private S3Service s3Service;
@EventListener(ApplicationReadyEvent.class)
public void checkStorageServices() {
log.info("=== 存储服务健康检查开始 ===");
// 检查OSS服务
try {
if (ossService != null) {
log.info("✓ OSS服务已启用");
} else {
log.warn("✗ OSS服务未启用");
}
} catch (Exception e) {
log.error("✗ OSS服务检查失败: {}", e.getMessage());
}
// 检查S3服务
try {
if (s3Service != null) {
log.info("✓ S3/MinIO服务已启用");
} else {
log.warn("✗ S3/MinIO服务未启用 (如需启用请配置zlt.file-server.s3.enabled=true)");
}
} catch (Exception e) {
log.error("✗ S3服务检查失败: {}", e.getMessage());
}
// 检查时间窗口存储服务
try {
if (ossService != null) {
log.info("✓ 时间窗口智能存储服务已启用");
log.info(" - 热数据存储: OSS");
log.info(" - 冷数据存储: {}", s3Service != null ? "S3/MinIO" : "未配置");
} else {
log.warn("✗ 时间窗口智能存储服务未启用");
}
} catch (Exception e) {
log.error("✗ 时间窗口存储服务检查失败: {}", e.getMessage());
}
log.info("=== 存储服务健康检查完成 ===");
}
/**
* 获取存储服务状态
*/
public String getStorageStatus() {
StringBuilder status = new StringBuilder();
status.append("存储服务状态:\n");
status.append("- OSS服务: ").append(ossService != null ? "已启用" : "未启用").append("\n");
status.append("- S3服务: ").append(s3Service != null ? "已启用" : "未启用").append("\n");
status.append("- 时间窗口存储: ").append(ossService != null ? "已启用" : "未启用");
return status.toString();
}
}
@@ -0,0 +1,305 @@
package com.central.file.service;
import com.central.common.model.FileInfo;
import com.central.file.service.impl.OssService;
import com.central.file.service.impl.S3Service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
/**
* 时间窗口智能存储服务
* 根据文件创建时间自动选择存储位置:
* - 热数据(30天内):存储在OSS,访问速度快
* - 冷数据(30天后):迁移到MinIO,降低成本
*
* @author system
*/
@Slf4j
@Service
public class TimeWindowStorageService {
@Autowired
private OssService ossService;
@Autowired(required = false)
@Qualifier("s3FileService")
private S3Service s3Service;
// 配置参数
@Value("${zlt.storage.hot-data-days:30}")
private int hotDataDays; // 热数据保留天数,默认30天
@Value("${zlt.storage.enable-time-window:true}")
private boolean enableTimeWindow; // 是否启用时间窗口存储
/**
* 智能获取文件访问URL
* 根据文件创建时间自动选择存储位置
*
* @param fileId 文件ID
* @return 访问URL
*/
public String getSmartViewUrl(String fileId) {
try {
// 1. 获取文件信息
FileInfo fileInfo = ossService.getFileInfo(fileId);
if (fileInfo == null) {
log.warn("文件不存在: fileId={}", fileId);
return "";
}
// 2. 判断存储类型
String storageType = getStorageTypeByTime(fileInfo);
// 3. 根据存储类型获取URL
String viewUrl = getViewUrlByStorageType(fileInfo, storageType);
log.debug("智能存储查询成功: fileId={}, storageType={}, url={}",
fileId, storageType, viewUrl);
return viewUrl;
} catch (Exception e) {
log.error("智能存储查询失败: fileId={}, error={}", fileId, e.getMessage(), e);
return "";
}
}
/**
* 智能获取文件访问URL(通过路径)
*
* @param filePath 文件路径
* @return 访问URL
*/
public String getSmartViewUrlByPath(String filePath) {
try {
// 1. 根据路径特征判断存储类型
if (isS3Path(filePath)) {
log.debug("S3路径,直接查询S3: path={}", filePath);
return queryFromS3ByPath(filePath);
} else if (isOssPath(filePath)) {
log.debug("OSS路径,直接查询OSS: path={}", filePath);
return ossService.getViewUrlByPath(filePath);
}
// 2. 路径特征不明确,尝试智能查询
log.debug("路径特征不明确,尝试智能查询: path={}", filePath);
return getViewUrlByFallback(filePath);
} catch (Exception e) {
log.error("智能存储查询失败: path={}, error={}", filePath, e.getMessage(), e);
return "";
}
}
/**
* 根据文件创建时间判断存储类型
*/
private String getStorageTypeByTime(FileInfo fileInfo) {
if (!enableTimeWindow) {
// 时间窗口功能关闭,使用默认OSS存储
return "OSS";
}
if (fileInfo.getCreateTime() == null) {
log.warn("文件创建时间为空,使用默认OSS存储: fileId={}", fileInfo.getId());
return "OSS";
}
// 计算文件创建时间距离现在的天数
LocalDateTime createTime = fileInfo.getCreateTime().toInstant()
.atZone(java.time.ZoneId.systemDefault())
.toLocalDateTime();
LocalDateTime now = LocalDateTime.now();
long daysDiff = ChronoUnit.DAYS.between(createTime, now);
if (daysDiff <= hotDataDays) {
// 热数据,使用OSS
log.debug("热数据,使用OSS存储: fileId={}, daysDiff={}", fileInfo.getId(), daysDiff);
return "OSS";
} else {
// 冷数据,使用S3(MinIO)
log.debug("冷数据,使用S3存储: fileId={}, daysDiff={}", fileInfo.getId(), daysDiff);
return "S3";
}
}
/**
* 根据存储类型获取访问URL
*/
private String getViewUrlByStorageType(FileInfo fileInfo, String storageType) {
if ("S3".equals(storageType)) {
// 冷数据,优先从S3查询
String s3Url = queryFromS3(fileInfo);
if (s3Url != null && !s3Url.isEmpty()) {
return s3Url;
}
// S3查询失败,降级到OSS
log.warn("S3查询失败,降级到OSS: fileId={}", fileInfo.getId());
return queryFromOss(fileInfo);
} else {
// 热数据,优先从OSS查询
String ossUrl = queryFromOss(fileInfo);
if (ossUrl != null && !ossUrl.isEmpty()) {
return ossUrl;
}
// OSS查询失败,降级到S3
log.warn("OSS查询失败,降级到S3: fileId={}", fileInfo.getId());
return queryFromS3(fileInfo);
}
}
/**
* 从OSS查询文件URL
*/
private String queryFromOss(FileInfo fileInfo) {
try {
return ossService.getViewUrlByPath(fileInfo.getPath());
} catch (Exception e) {
log.warn("从OSS查询失败: fileId={}, error={}", fileInfo.getId(), e.getMessage());
return "";
}
}
/**
* 从S3查询文件URL
*/
private String queryFromS3(FileInfo fileInfo) {
try {
if (s3Service != null) {
return s3Service.getViewUrlByPath(fileInfo.getPath());
} else {
log.warn("S3Service未配置,无法查询S3: fileId={}", fileInfo.getId());
return "";
}
} catch (Exception e) {
log.warn("从S3查询失败: fileId={}, error={}", fileInfo.getId(), e.getMessage());
return "";
}
}
/**
* 从S3查询文件URL(通过路径)
*/
private String queryFromS3ByPath(String filePath) {
try {
if (s3Service != null) {
return s3Service.getViewUrlByPath(filePath);
} else {
log.warn("S3Service未配置,无法查询S3: path={}", filePath);
return "";
}
} catch (Exception e) {
log.warn("从S3查询失败: path={}, error={}", filePath, e.getMessage());
return "";
}
}
/**
* 降级查询策略
*/
private String getViewUrlByFallback(String filePath) {
// 先尝试OSS
try {
String ossUrl = ossService.getViewUrlByPath(filePath);
if (ossUrl != null && !ossUrl.isEmpty()) {
log.debug("OSS降级查询成功: path={}", filePath);
return ossUrl;
}
} catch (Exception e) {
log.warn("OSS降级查询失败: path={}, error={}", filePath, e.getMessage());
}
// 再尝试S3
try {
String s3Url = queryFromS3ByPath(filePath);
if (s3Url != null && !s3Url.isEmpty()) {
log.debug("S3降级查询成功: path={}", filePath);
return s3Url;
}
} catch (Exception e) {
log.warn("S3降级查询失败: path={}, error={}", filePath, e.getMessage());
}
log.warn("所有存储查询都失败: path={}", filePath);
return "";
}
/**
* 判断是否为S3路径
*/
private boolean isS3Path(String path) {
return path != null && (
path.contains("s3://") ||
path.contains("minio") ||
path.startsWith("cold-storage") ||
path.contains("S3")
);
}
/**
* 判断是否为OSS路径
*/
private boolean isOssPath(String path) {
return path != null && (
path.contains("oss://") ||
path.contains("aliyun") ||
path.contains("ali-oss") ||
path.contains("OSS")
);
}
/**
* 检查文件是否需要迁移
*
* @param fileInfo 文件信息
* @return 是否需要迁移
*/
public boolean needMigration(FileInfo fileInfo) {
if (!enableTimeWindow) {
return false;
}
String storageType = getStorageTypeByTime(fileInfo);
return "S3".equals(storageType) && !isFileInS3(fileInfo);
}
/**
* 检查文件是否已在S3中
*/
private boolean isFileInS3(FileInfo fileInfo) {
try {
// 检查存储类型
if (fileInfo.getStorageType() != null &&
(fileInfo.getStorageType().contains("S3") || fileInfo.getStorageType().contains("MINIO"))) {
return true;
}
// 检查路径特征
if (fileInfo.getPath() != null &&
(fileInfo.getPath().contains("s3://") || fileInfo.getPath().contains("minio"))) {
return true;
}
return false;
} catch (Exception e) {
log.warn("检查文件S3状态失败: fileId={}", fileInfo.getId(), e);
return false;
}
}
/**
* 获取存储统计信息
*/
public String getStorageStatistics() {
String s3Status = s3Service != null ? "已启用" : "未配置";
return String.format("时间窗口存储服务 - 热数据天数: %d, 启用状态: %s, S3服务: %s",
hotDataDays, enableTimeWindow, s3Status);
}
}
@@ -10,6 +10,7 @@ import com.central.oss.properties.FileServerProperties;
import com.central.oss.template.OssTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
@@ -27,6 +28,7 @@ import java.util.List;
*/
@Slf4j
@Service
@Primary
@ConditionalOnProperty(prefix = FileServerProperties.PREFIX, name = "type", havingValue = FileServerProperties.TYPE_OSS)
public class OssService extends AbstractIFileService {
@@ -8,6 +8,7 @@ import com.central.oss.properties.FileServerProperties;
import com.central.oss.template.S3Template;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
@@ -24,8 +25,9 @@ import java.util.List;
* Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Service
@ConditionalOnProperty(prefix = com.central.oss.properties.FileServerProperties.PREFIX, name = "type", havingValue = FileServerProperties.TYPE_S3)
@Service("s3FileService")
@ConditionalOnClass(name = "com.amazonaws.services.s3.AmazonS3")
@ConditionalOnProperty(prefix = "zlt.file-server.s3", name = "enabled", havingValue = "true", matchIfMissing = false)
public class S3Service extends AbstractIFileService {
@Resource
private S3Template s3Template;