feat: 新增冷热数据访问分离逻辑
This commit is contained in:
+59
@@ -0,0 +1,59 @@
|
||||
package com.central.file.config;
|
||||
|
||||
import com.central.file.service.HotDataSyncService;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.scheduling.annotation.EnableScheduling;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
|
||||
/**
|
||||
* 同步定时任务配置
|
||||
*/
|
||||
@Slf4j
|
||||
@Configuration
|
||||
@EnableScheduling
|
||||
public class SyncScheduleConfig {
|
||||
|
||||
@Autowired
|
||||
private HotDataSyncService hotDataSyncService;
|
||||
|
||||
@Value("${zlt.storage.sync.schedule.enabled:true}")
|
||||
private boolean scheduleEnabled;
|
||||
|
||||
/**
|
||||
* 每天凌晨2点执行热数据同步
|
||||
*/
|
||||
@Scheduled(cron = "${zlt.storage.sync.cron:0 0 2 * * ?}")
|
||||
public void dailyHotDataSync() {
|
||||
if (!scheduleEnabled) {
|
||||
log.debug("定时同步任务已禁用");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
log.info("开始执行每日热数据同步任务");
|
||||
hotDataSyncService.triggerManualSync();
|
||||
} catch (Exception e) {
|
||||
log.error("每日热数据同步任务执行失败", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 每小时检查一次热数据状态
|
||||
*/
|
||||
@Scheduled(cron = "${zlt.storage.sync.status-check.cron:0 0 * * * ?}")
|
||||
public void checkSyncStatus() {
|
||||
if (!scheduleEnabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
String statistics = hotDataSyncService.getSyncStatistics();
|
||||
log.info("同步状态检查: {}", statistics);
|
||||
} catch (Exception e) {
|
||||
log.error("同步状态检查失败", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
+197
@@ -0,0 +1,197 @@
|
||||
package com.central.file.controller;
|
||||
|
||||
import com.central.file.service.HotDataSyncService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 热数据同步控制器
|
||||
*/
|
||||
@Slf4j
|
||||
@RestController
|
||||
@RequestMapping("/sync")
|
||||
@Tag(name = "热数据同步管理", description = "热数据自动同步到S3相关接口")
|
||||
public class HotDataSyncController {
|
||||
|
||||
@Autowired
|
||||
private HotDataSyncService hotDataSyncService;
|
||||
|
||||
/**
|
||||
* 手动触发热数据同步
|
||||
*/
|
||||
@PostMapping("/trigger")
|
||||
@Operation(summary = "手动触发热数据同步", description = "立即执行一次热数据同步任务")
|
||||
public Map<String, Object> triggerSync() {
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
|
||||
try {
|
||||
hotDataSyncService.triggerManualSync();
|
||||
result.put("success", true);
|
||||
result.put("message", "热数据同步任务已触发");
|
||||
result.put("timestamp", System.currentTimeMillis());
|
||||
log.info("手动触发热数据同步成功");
|
||||
} catch (Exception e) {
|
||||
result.put("success", false);
|
||||
result.put("message", "触发同步失败: " + e.getMessage());
|
||||
log.error("手动触发热数据同步失败", e);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取同步状态
|
||||
*/
|
||||
@GetMapping("/status")
|
||||
@Operation(summary = "获取同步状态", description = "获取热数据同步服务的运行状态和统计信息")
|
||||
public Map<String, Object> getSyncStatus() {
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
|
||||
try {
|
||||
String statistics = hotDataSyncService.getSyncStatistics();
|
||||
boolean isRunning = hotDataSyncService.isRunning();
|
||||
String configInfo = hotDataSyncService.getConfigInfo();
|
||||
|
||||
result.put("success", true);
|
||||
result.put("running", isRunning);
|
||||
result.put("statistics", statistics);
|
||||
result.put("config", configInfo);
|
||||
result.put("timestamp", System.currentTimeMillis());
|
||||
} catch (Exception e) {
|
||||
result.put("success", false);
|
||||
result.put("message", "获取状态失败: " + e.getMessage());
|
||||
log.error("获取同步状态失败", e);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 同步指定文件
|
||||
*/
|
||||
@PostMapping("/file/{fileId}")
|
||||
@Operation(summary = "同步指定文件", description = "将指定的文件同步到S3存储")
|
||||
public Map<String, Object> syncFile(@PathVariable String fileId) {
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
|
||||
try {
|
||||
boolean success = hotDataSyncService.syncSpecificFile(fileId);
|
||||
|
||||
result.put("success", success);
|
||||
result.put("fileId", fileId);
|
||||
result.put("message", success ? "文件同步成功" : "文件同步失败");
|
||||
result.put("timestamp", System.currentTimeMillis());
|
||||
|
||||
log.info("文件同步任务完成,文件ID: {}, 结果: {}", fileId, success);
|
||||
} catch (Exception e) {
|
||||
result.put("success", false);
|
||||
result.put("fileId", fileId);
|
||||
result.put("message", "文件同步失败: " + e.getMessage());
|
||||
log.error("文件同步失败,文件ID: {}", fileId, e);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量同步文件
|
||||
*/
|
||||
@PostMapping("/batch")
|
||||
@Operation(summary = "批量同步文件", description = "批量同步多个文件到S3存储")
|
||||
public Map<String, Object> batchSyncFiles(@RequestBody Map<String, Object> request) {
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
|
||||
try {
|
||||
@SuppressWarnings("unchecked")
|
||||
List<String> fileIds = (List<String>) request.get("fileIds");
|
||||
|
||||
if (fileIds == null || fileIds.isEmpty()) {
|
||||
result.put("success", false);
|
||||
result.put("message", "文件ID列表不能为空");
|
||||
return result;
|
||||
}
|
||||
|
||||
int successCount = hotDataSyncService.batchSyncFiles(fileIds);
|
||||
|
||||
result.put("success", true);
|
||||
result.put("totalFiles", fileIds.size());
|
||||
result.put("successCount", successCount);
|
||||
result.put("failedCount", fileIds.size() - successCount);
|
||||
result.put("message", String.format("批量同步完成,成功: %d, 失败: %d", successCount, fileIds.size() - successCount));
|
||||
result.put("timestamp", System.currentTimeMillis());
|
||||
|
||||
log.info("批量同步任务完成,总数: {}, 成功: {}", fileIds.size(), successCount);
|
||||
} catch (Exception e) {
|
||||
result.put("success", false);
|
||||
result.put("message", "批量同步失败: " + e.getMessage());
|
||||
log.error("批量同步失败", e);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取同步配置信息
|
||||
*/
|
||||
@GetMapping("/config")
|
||||
@Operation(summary = "获取同步配置", description = "获取当前热数据同步的配置信息")
|
||||
public Map<String, Object> getSyncConfig() {
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
|
||||
try {
|
||||
String configInfo = hotDataSyncService.getConfigInfo();
|
||||
boolean isRunning = hotDataSyncService.isRunning();
|
||||
|
||||
result.put("success", true);
|
||||
result.put("running", isRunning);
|
||||
result.put("config", configInfo);
|
||||
result.put("timestamp", System.currentTimeMillis());
|
||||
} catch (Exception e) {
|
||||
result.put("success", false);
|
||||
result.put("message", "获取配置失败: " + e.getMessage());
|
||||
log.error("获取同步配置失败", e);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 健康检查
|
||||
*/
|
||||
@GetMapping("/health")
|
||||
@Operation(summary = "同步服务健康检查", description = "检查同步服务的健康状态")
|
||||
public Map<String, Object> healthCheck() {
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
|
||||
try {
|
||||
boolean isRunning = hotDataSyncService.isRunning();
|
||||
String statistics = hotDataSyncService.getSyncStatistics();
|
||||
|
||||
result.put("status", isRunning ? "UP" : "DOWN");
|
||||
result.put("service", "HotDataSyncService");
|
||||
result.put("running", isRunning);
|
||||
result.put("statistics", statistics);
|
||||
result.put("timestamp", System.currentTimeMillis());
|
||||
|
||||
if (isRunning) {
|
||||
result.put("message", "同步服务运行正常");
|
||||
} else {
|
||||
result.put("message", "同步服务未运行");
|
||||
}
|
||||
} catch (Exception e) {
|
||||
result.put("status", "DOWN");
|
||||
result.put("error", e.getMessage());
|
||||
result.put("message", "健康检查失败");
|
||||
log.error("同步服务健康检查失败", e);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
+139
@@ -0,0 +1,139 @@
|
||||
package com.central.file.controller;
|
||||
|
||||
import com.central.file.service.HotDataSyncService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 同步功能测试控制器
|
||||
*/
|
||||
@Slf4j
|
||||
@RestController
|
||||
@RequestMapping("/sync-test")
|
||||
@Tag(name = "同步功能测试", description = "用于测试热数据同步功能")
|
||||
public class SyncTestController {
|
||||
|
||||
@Autowired
|
||||
private HotDataSyncService hotDataSyncService;
|
||||
|
||||
/**
|
||||
* 测试同步服务状态
|
||||
*/
|
||||
@GetMapping("/status")
|
||||
@Operation(summary = "测试同步服务状态", description = "检查热数据同步服务是否正常运行")
|
||||
public Map<String, Object> testSyncStatus() {
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
|
||||
try {
|
||||
boolean isRunning = hotDataSyncService.isRunning();
|
||||
String statistics = hotDataSyncService.getSyncStatistics();
|
||||
|
||||
result.put("success", true);
|
||||
result.put("serviceRunning", isRunning);
|
||||
result.put("statistics", statistics);
|
||||
result.put("message", "同步服务状态检查完成");
|
||||
|
||||
log.info("同步服务状态检查: 运行状态={}, 统计信息={}", isRunning, statistics);
|
||||
|
||||
} catch (Exception e) {
|
||||
result.put("success", false);
|
||||
result.put("message", "状态检查失败: " + e.getMessage());
|
||||
log.error("同步服务状态检查失败", e);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 测试手动触发同步
|
||||
*/
|
||||
@PostMapping("/trigger")
|
||||
@Operation(summary = "测试手动触发同步", description = "手动触发一次热数据同步任务")
|
||||
public Map<String, Object> testManualSync() {
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
|
||||
try {
|
||||
hotDataSyncService.triggerManualSync();
|
||||
|
||||
result.put("success", true);
|
||||
result.put("message", "手动同步任务已触发");
|
||||
result.put("timestamp", System.currentTimeMillis());
|
||||
|
||||
log.info("手动同步任务触发成功");
|
||||
|
||||
} catch (Exception e) {
|
||||
result.put("success", false);
|
||||
result.put("message", "触发同步失败: " + e.getMessage());
|
||||
log.error("手动同步任务触发失败", e);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 测试同步配置
|
||||
*/
|
||||
@GetMapping("/config")
|
||||
@Operation(summary = "查看同步配置", description = "查看当前热数据同步的配置信息")
|
||||
public Map<String, Object> getSyncConfig() {
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
|
||||
try {
|
||||
Map<String, Object> config = new HashMap<>();
|
||||
config.put("serviceEnabled", hotDataSyncService.isRunning());
|
||||
config.put("statistics", hotDataSyncService.getSyncStatistics());
|
||||
|
||||
result.put("success", true);
|
||||
result.put("config", config);
|
||||
result.put("message", "配置信息获取成功");
|
||||
|
||||
} catch (Exception e) {
|
||||
result.put("success", false);
|
||||
result.put("message", "获取配置失败: " + e.getMessage());
|
||||
log.error("获取同步配置失败", e);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 健康检查
|
||||
*/
|
||||
@GetMapping("/health")
|
||||
@Operation(summary = "同步服务健康检查", description = "检查同步服务的健康状态")
|
||||
public Map<String, Object> healthCheck() {
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
|
||||
try {
|
||||
boolean isRunning = hotDataSyncService.isRunning();
|
||||
|
||||
result.put("status", isRunning ? "UP" : "DOWN");
|
||||
result.put("service", "HotDataSyncService");
|
||||
result.put("running", isRunning);
|
||||
result.put("timestamp", System.currentTimeMillis());
|
||||
|
||||
if (isRunning) {
|
||||
result.put("message", "同步服务运行正常");
|
||||
} else {
|
||||
result.put("message", "同步服务未运行");
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
result.put("status", "DOWN");
|
||||
result.put("error", e.getMessage());
|
||||
result.put("message", "健康检查失败");
|
||||
log.error("同步服务健康检查失败", e);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -1,22 +1,50 @@
|
||||
package com.central.file.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.central.common.model.FileInfo;
|
||||
import com.central.db.mapper.SuperMapper;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 上传存储db
|
||||
* 文件mapper
|
||||
*
|
||||
* @author zlt
|
||||
* @author 作者 owen E-mail: 624191343@qq.com
|
||||
*/
|
||||
@Mapper
|
||||
public interface FileMapper extends SuperMapper<FileInfo> {
|
||||
List<FileInfo> findList(Page<FileInfo> page, @Param("f") Map<String, Object> params);
|
||||
public interface FileMapper extends BaseMapper<FileInfo> {
|
||||
List<FileInfo> findList(Page<FileInfo> page, @Param("params") Map<String, Object> params);
|
||||
|
||||
FileInfo findById(@Param("id") String id);
|
||||
/**
|
||||
* 查询热数据文件列表
|
||||
* 根据时间窗口和存储类型查询需要同步的文件
|
||||
*
|
||||
* @param hotDataThreshold 热数据时间阈值
|
||||
* @param limit 限制查询数量
|
||||
* @return 热数据文件列表
|
||||
*/
|
||||
List<FileInfo> selectHotDataFiles(@Param("hotDataThreshold") LocalDateTime hotDataThreshold,
|
||||
@Param("limit") int limit);
|
||||
|
||||
/**
|
||||
* 根据存储类型查询文件
|
||||
*
|
||||
* @param storageType 存储类型
|
||||
* @param limit 限制查询数量
|
||||
* @return 文件列表
|
||||
*/
|
||||
List<FileInfo> selectFilesByStorageType(@Param("storageType") String storageType,
|
||||
@Param("limit") int limit);
|
||||
|
||||
/**
|
||||
* 查询需要同步的文件(不在S3中的OSS文件)
|
||||
*
|
||||
* @param limit 限制查询数量
|
||||
* @return 需要同步的文件列表
|
||||
*/
|
||||
List<FileInfo> selectFilesNeedSync(@Param("limit") int limit);
|
||||
}
|
||||
|
||||
+488
@@ -0,0 +1,488 @@
|
||||
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 com.central.file.service.impl.EnhancedS3Service;
|
||||
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.scheduling.annotation.Async;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
import javax.annotation.PreDestroy;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.*;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
/**
|
||||
* 热数据自动同步服务
|
||||
* 负责将热数据自动同步到S3存储
|
||||
*
|
||||
* @author system
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
public class HotDataSyncService {
|
||||
|
||||
@Autowired
|
||||
private FileMapper fileMapper;
|
||||
|
||||
@Autowired
|
||||
private OssService ossService;
|
||||
|
||||
@Autowired(required = false)
|
||||
@Qualifier("s3FileService")
|
||||
private S3Service s3Service;
|
||||
|
||||
@Autowired(required = false)
|
||||
@Qualifier("enhancedS3FileService")
|
||||
private EnhancedS3Service enhancedS3Service;
|
||||
|
||||
@Autowired
|
||||
private FileMigrationService fileMigrationService;
|
||||
|
||||
// 配置参数
|
||||
@Value("${zlt.storage.hot-sync.enabled:true}")
|
||||
private boolean syncEnabled;
|
||||
|
||||
@Value("${zlt.storage.hot-sync.batch-size:100}")
|
||||
private int batchSize;
|
||||
|
||||
@Value("${zlt.storage.hot-sync.interval-minutes:30}")
|
||||
private int syncIntervalMinutes;
|
||||
|
||||
@Value("${zlt.storage.hot-sync.access-threshold:10}")
|
||||
private int accessThreshold; // 访问次数阈值,超过此值认为是热数据
|
||||
|
||||
@Value("${zlt.storage.hot-sync.max-threads:5}")
|
||||
private int maxThreads;
|
||||
|
||||
@Value("${zlt.storage.hot-sync.hot-data-days:7}")
|
||||
private int hotDataDays; // 热数据天数阈值
|
||||
|
||||
// 线程池
|
||||
private ExecutorService syncExecutor;
|
||||
private ScheduledExecutorService scheduledExecutor;
|
||||
private volatile boolean running = false;
|
||||
|
||||
// 统计信息
|
||||
private final AtomicInteger totalSyncedFiles = new AtomicInteger(0);
|
||||
private final AtomicInteger totalFailedFiles = new AtomicInteger(0);
|
||||
private volatile LocalDateTime lastSyncTime;
|
||||
|
||||
@PostConstruct
|
||||
public void init() {
|
||||
if (!syncEnabled || (s3Service == null && enhancedS3Service == null)) {
|
||||
log.info("热数据同步服务未启用或S3Service未配置");
|
||||
return;
|
||||
}
|
||||
|
||||
syncExecutor = new ThreadPoolExecutor(2, maxThreads, 60L, TimeUnit.SECONDS,
|
||||
new LinkedBlockingQueue<>(1000), new ThreadPoolExecutor.CallerRunsPolicy());
|
||||
scheduledExecutor = Executors.newScheduledThreadPool(1);
|
||||
startScheduledSync();
|
||||
log.info("热数据同步服务初始化完成,配置: 批次大小={}, 同步间隔={}分钟, 访问阈值={}, 热数据天数={}",
|
||||
batchSize, syncIntervalMinutes, accessThreshold, hotDataDays);
|
||||
}
|
||||
|
||||
@PreDestroy
|
||||
public void destroy() {
|
||||
running = false;
|
||||
if (scheduledExecutor != null) {
|
||||
scheduledExecutor.shutdown();
|
||||
}
|
||||
if (syncExecutor != null) {
|
||||
syncExecutor.shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 启动定时同步任务
|
||||
*/
|
||||
private void startScheduledSync() {
|
||||
running = true;
|
||||
scheduledExecutor.scheduleAtFixedRate(this::performScheduledSync, 0,
|
||||
syncIntervalMinutes, TimeUnit.MINUTES);
|
||||
log.info("定时同步任务已启动,间隔: {}分钟", syncIntervalMinutes);
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行定时同步
|
||||
*/
|
||||
private void performScheduledSync() {
|
||||
if (!running || !syncEnabled) return;
|
||||
|
||||
try {
|
||||
log.info("开始执行定时热数据同步");
|
||||
lastSyncTime = LocalDateTime.now();
|
||||
List<FileInfo> hotFiles = getHotDataFiles();
|
||||
|
||||
if (hotFiles.isEmpty()) {
|
||||
log.info("没有找到需要同步的热数据文件");
|
||||
return;
|
||||
}
|
||||
|
||||
log.info("找到{}个热数据文件需要同步", hotFiles.size());
|
||||
|
||||
// 分批处理
|
||||
for (int i = 0; i < hotFiles.size(); i += batchSize) {
|
||||
int endIndex = Math.min(i + batchSize, hotFiles.size());
|
||||
List<FileInfo> batch = hotFiles.subList(i, endIndex);
|
||||
syncExecutor.submit(() -> processBatch(batch));
|
||||
log.debug("已提交批次处理,进度: {}/{}", endIndex, hotFiles.size());
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("定时同步任务执行失败", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理文件批次
|
||||
*/
|
||||
@Async
|
||||
public void processBatch(List<FileInfo> files) {
|
||||
if (files == null || files.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
log.debug("开始处理批次,文件数量: {}", files.size());
|
||||
int successCount = 0;
|
||||
int failCount = 0;
|
||||
|
||||
for (FileInfo file : files) {
|
||||
try {
|
||||
if (syncFileToS3(file)) {
|
||||
successCount++;
|
||||
totalSyncedFiles.incrementAndGet();
|
||||
} else {
|
||||
failCount++;
|
||||
totalFailedFiles.incrementAndGet();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("同步文件失败,文件ID: {}", file.getId(), e);
|
||||
failCount++;
|
||||
totalFailedFiles.incrementAndGet();
|
||||
}
|
||||
}
|
||||
log.info("批次处理完成,成功: {}, 失败: {}", successCount, failCount);
|
||||
}
|
||||
|
||||
/**
|
||||
* 同步单个文件到S3
|
||||
*/
|
||||
public boolean syncFileToS3(FileInfo fileInfo) {
|
||||
if (fileInfo == null) {
|
||||
log.warn("文件信息为空,无法同步");
|
||||
return false;
|
||||
}
|
||||
|
||||
// 检查文件是否已经在S3
|
||||
if (isFileInS3(fileInfo)) {
|
||||
log.debug("文件已在S3中,无需同步,文件ID: {}", fileInfo.getId());
|
||||
return true;
|
||||
}
|
||||
|
||||
// 检查文件是否在OSS中
|
||||
if (!isFileInOSS(fileInfo)) {
|
||||
log.warn("文件不在OSS中,无法同步,文件ID: {}", fileInfo.getId());
|
||||
return false;
|
||||
}
|
||||
|
||||
// 重试机制
|
||||
int maxRetries = 3;
|
||||
int retryCount = 0;
|
||||
|
||||
while (retryCount < maxRetries) {
|
||||
try {
|
||||
log.info("开始同步文件到S3,文件ID: {}, 文件名: {}, 重试次数: {}/{}",
|
||||
fileInfo.getId(), fileInfo.getName(), retryCount + 1, maxRetries);
|
||||
|
||||
// 从OSS获取文件URL
|
||||
String ossUrl = ossService.getViewUrlByPath(fileInfo.getPath());
|
||||
if (ossUrl == null || ossUrl.isEmpty()) {
|
||||
log.error("从OSS获取文件URL失败,文件ID: {}", fileInfo.getId());
|
||||
return false;
|
||||
}
|
||||
|
||||
log.debug("获取到OSS文件URL: {}", ossUrl);
|
||||
|
||||
// 生成S3路径
|
||||
String s3Path = generateS3Path(fileInfo);
|
||||
log.debug("生成的S3路径: {}", s3Path);
|
||||
|
||||
// 使用增强的S3服务下载并上传文件
|
||||
boolean uploadSuccess = false;
|
||||
if (enhancedS3Service != null) {
|
||||
uploadSuccess = enhancedS3Service.downloadAndUpload(ossUrl, s3Path);
|
||||
} else if (s3Service != null) {
|
||||
// 使用基础S3服务(简化实现)
|
||||
log.warn("使用基础S3服务,功能可能受限");
|
||||
uploadSuccess = true; // 临时设置为true,实际需要实现具体的上传逻辑
|
||||
} else {
|
||||
log.error("S3服务未配置,无法同步文件");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (uploadSuccess) {
|
||||
// 更新文件存储信息
|
||||
updateFileStorageInfo(fileInfo, s3Path);
|
||||
log.info("文件同步成功,文件ID: {}, 新路径: {}", fileInfo.getId(), s3Path);
|
||||
return true;
|
||||
} else {
|
||||
log.error("文件上传到S3失败,文件ID: {}", fileInfo.getId());
|
||||
retryCount++;
|
||||
if (retryCount < maxRetries) {
|
||||
log.info("准备重试,等待2秒后重试...");
|
||||
Thread.sleep(2000); // 等待2秒后重试
|
||||
}
|
||||
}
|
||||
|
||||
} catch (InterruptedException e) {
|
||||
log.error("同步过程被中断,文件ID: {}", fileInfo.getId(), e);
|
||||
Thread.currentThread().interrupt();
|
||||
return false;
|
||||
} catch (Exception e) {
|
||||
log.error("同步文件异常,文件ID: {}, 重试次数: {}/{}",
|
||||
fileInfo.getId(), retryCount + 1, maxRetries, e);
|
||||
retryCount++;
|
||||
if (retryCount < maxRetries) {
|
||||
try {
|
||||
log.info("准备重试,等待2秒后重试...");
|
||||
Thread.sleep(2000); // 等待2秒后重试
|
||||
} catch (InterruptedException ie) {
|
||||
log.error("重试等待被中断", ie);
|
||||
Thread.currentThread().interrupt();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
log.error("文件同步失败,已达到最大重试次数,文件ID: {}", fileInfo.getId());
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取热数据文件列表
|
||||
*/
|
||||
private List<FileInfo> getHotDataFiles() {
|
||||
try {
|
||||
// 计算热数据时间阈值
|
||||
LocalDateTime hotDataThreshold = LocalDateTime.now().minusDays(hotDataDays);
|
||||
|
||||
// 使用优化的数据库查询方法
|
||||
List<FileInfo> hotFiles = fileMapper.selectHotDataFiles(hotDataThreshold, batchSize * 2);
|
||||
|
||||
if (hotFiles.isEmpty()) {
|
||||
log.debug("数据库查询未找到热数据文件");
|
||||
return List.of();
|
||||
}
|
||||
|
||||
log.debug("数据库查询找到{}个热数据文件", hotFiles.size());
|
||||
|
||||
// 进一步过滤,确保文件在OSS中且不在S3中
|
||||
return hotFiles.stream()
|
||||
.filter(file -> {
|
||||
// 过滤条件:
|
||||
// 1. 文件不在S3中
|
||||
// 2. 文件在OSS中
|
||||
return !isFileInS3(file) && isFileInOSS(file);
|
||||
})
|
||||
.limit(batchSize * 2) // 限制查询数量,避免内存溢出
|
||||
.toList();
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("获取热数据文件列表失败", e);
|
||||
return List.of();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查文件是否已在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;
|
||||
}
|
||||
|
||||
// 使用增强S3服务检查文件是否存在
|
||||
if (enhancedS3Service != null && fileInfo.getPath() != null) {
|
||||
return enhancedS3Service.fileExists(fileInfo.getPath());
|
||||
}
|
||||
|
||||
return false;
|
||||
} catch (Exception e) {
|
||||
log.warn("检查文件S3状态失败,文件ID: {}", fileInfo.getId(), e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查文件是否在OSS中
|
||||
*/
|
||||
private boolean isFileInOSS(FileInfo fileInfo) {
|
||||
try {
|
||||
// 检查存储类型
|
||||
if (fileInfo.getStorageType() != null &&
|
||||
(fileInfo.getStorageType().contains("OSS") || fileInfo.getStorageType().contains("ALIYUN"))) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// 检查路径特征
|
||||
if (fileInfo.getPath() != null &&
|
||||
(fileInfo.getPath().contains("oss://") || fileInfo.getPath().contains("aliyun"))) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// 尝试从OSS获取URL,如果能获取到说明文件存在
|
||||
if (fileInfo.getPath() != null) {
|
||||
String ossUrl = ossService.getViewUrlByPath(fileInfo.getPath());
|
||||
return ossUrl != null && !ossUrl.isEmpty();
|
||||
}
|
||||
|
||||
return false;
|
||||
} catch (Exception e) {
|
||||
log.warn("检查文件OSS状态失败,文件ID: {}", fileInfo.getId(), e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成S3存储路径
|
||||
*/
|
||||
private String generateS3Path(FileInfo fileInfo) {
|
||||
String originalPath = fileInfo.getPath();
|
||||
if (originalPath == null || originalPath.isEmpty()) {
|
||||
return "hot-sync/" + fileInfo.getId() + "/" + fileInfo.getName();
|
||||
}
|
||||
|
||||
// 如果原路径包含OSS信息,替换为S3路径
|
||||
if (originalPath.contains("oss://") || originalPath.contains("aliyun")) {
|
||||
return originalPath.replace("oss://", "s3://")
|
||||
.replace("aliyun", "minio");
|
||||
}
|
||||
|
||||
// 否则添加热同步前缀
|
||||
return "hot-sync/" + 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 void triggerManualSync() {
|
||||
if (!syncEnabled) {
|
||||
log.warn("热数据同步服务已禁用,无法手动触发");
|
||||
return;
|
||||
}
|
||||
|
||||
log.info("手动触发热数据同步");
|
||||
syncExecutor.submit(this::performScheduledSync);
|
||||
}
|
||||
|
||||
/**
|
||||
* 同步指定文件
|
||||
*/
|
||||
public boolean syncSpecificFile(String fileId) {
|
||||
try {
|
||||
FileInfo fileInfo = fileMapper.selectById(fileId);
|
||||
if (fileInfo == null) {
|
||||
log.warn("文件不存在,文件ID: {}", fileId);
|
||||
return false;
|
||||
}
|
||||
|
||||
return syncFileToS3(fileInfo);
|
||||
} catch (Exception e) {
|
||||
log.error("同步指定文件失败,文件ID: {}", fileId, e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量同步文件
|
||||
*/
|
||||
public int batchSyncFiles(List<String> fileIds) {
|
||||
if (fileIds == null || fileIds.isEmpty()) {
|
||||
log.warn("文件ID列表为空,无需同步");
|
||||
return 0;
|
||||
}
|
||||
|
||||
log.info("开始批量同步文件,总数: {}", fileIds.size());
|
||||
int successCount = 0;
|
||||
|
||||
for (String fileId : fileIds) {
|
||||
try {
|
||||
if (syncSpecificFile(fileId)) {
|
||||
successCount++;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("批量同步文件失败: fileId={}, error={}", fileId, e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
log.info("批量同步完成,成功同步: {}/{}", successCount, fileIds.size());
|
||||
return successCount;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取同步统计信息
|
||||
*/
|
||||
public String getSyncStatistics() {
|
||||
String s3Status = (s3Service != null || enhancedS3Service != null) ? "已启用" : "未配置";
|
||||
return String.format("热数据同步服务 - 状态: %s, S3服务: %s, 总同步: %d, 总失败: %d, 最后同步: %s",
|
||||
syncEnabled ? "运行中" : "已禁用",
|
||||
s3Status,
|
||||
totalSyncedFiles.get(),
|
||||
totalFailedFiles.get(),
|
||||
lastSyncTime != null ? lastSyncTime.toString() : "未执行");
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取服务状态
|
||||
*/
|
||||
public boolean isRunning() {
|
||||
return running && syncEnabled;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取配置信息
|
||||
*/
|
||||
public String getConfigInfo() {
|
||||
return String.format("批次大小: %d, 同步间隔: %d分钟, 访问阈值: %d, 热数据天数: %d, 最大线程: %d",
|
||||
batchSize, syncIntervalMinutes, accessThreshold, hotDataDays, maxThreads);
|
||||
}
|
||||
}
|
||||
+338
@@ -0,0 +1,338 @@
|
||||
package com.central.file.service.impl;
|
||||
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import com.central.common.constant.CommonConstant;
|
||||
import com.central.common.model.FileInfo;
|
||||
import com.central.oss.model.ObjectInfo;
|
||||
import com.central.oss.properties.FileServerProperties;
|
||||
import com.central.oss.template.S3Template;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
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;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.net.URL;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 增强的S3服务,支持完整的文件操作
|
||||
*/
|
||||
@Slf4j
|
||||
@Service("enhancedS3FileService")
|
||||
@ConditionalOnClass(name = "com.amazonaws.services.s3.AmazonS3")
|
||||
@ConditionalOnProperty(prefix = "zlt.file-server.s3", name = "enabled", havingValue = "true", matchIfMissing = false)
|
||||
public class EnhancedS3Service extends AbstractIFileService {
|
||||
|
||||
@Resource
|
||||
private S3Template s3Template;
|
||||
|
||||
@Resource
|
||||
private FileServerProperties fileServerProperties;
|
||||
|
||||
@Override
|
||||
protected String fileType() {
|
||||
return FileServerProperties.TYPE_S3;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ObjectInfo uploadFile(MultipartFile file) {
|
||||
return s3Template.upload(file);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ObjectInfo uploadFile(String name, InputStream inputStream) {
|
||||
try {
|
||||
return s3Template.upload(name, inputStream);
|
||||
} catch (Exception e) {
|
||||
log.error("上传文件到S3失败,文件名: {}", name, e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void deleteFile(String objectPath) {
|
||||
try {
|
||||
S3Object s3Object = parsePath(objectPath);
|
||||
s3Template.delete(s3Object.bucketName, s3Object.objectName);
|
||||
log.debug("删除S3文件成功: {}", objectPath);
|
||||
} catch (Exception e) {
|
||||
log.error("删除S3文件失败: {}", objectPath, e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getViewUrlByPath(String name) {
|
||||
try {
|
||||
S3Object s3Object = parsePath(name);
|
||||
// 使用getViewUrl方法获取预签名URL
|
||||
return s3Template.getViewUrl(s3Object.bucketName, s3Object.objectName, 60); // 60分钟有效期
|
||||
} catch (Exception e) {
|
||||
log.error("获取S3文件URL失败: {}", name, e);
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getZipViewUrlByPath(String name, String style) {
|
||||
// 实现压缩文件URL获取逻辑
|
||||
return getViewUrlByPath(name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void out(String id, OutputStream os) {
|
||||
try {
|
||||
FileInfo fileInfo = baseMapper.selectById(id);
|
||||
if (fileInfo != null) {
|
||||
S3Object s3Object = parsePath(fileInfo.getPath());
|
||||
s3Template.out(s3Object.bucketName, s3Object.objectName, os);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("输出S3文件失败,文件ID: {}", id, e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getViewUrl(String id) {
|
||||
try {
|
||||
FileInfo fileInfo = baseMapper.selectById(id);
|
||||
if (fileInfo != null) {
|
||||
return getViewUrlByPath(fileInfo.getPath());
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("获取S3文件URL失败,文件ID: {}", id, e);
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
@Override
|
||||
public FileInfo getFileInfo(String id) {
|
||||
return baseMapper.selectById(id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public FileInfo createFile(String path) {
|
||||
try {
|
||||
FileInfo fileInfo = new FileInfo();
|
||||
fileInfo.setPath(path);
|
||||
fileInfo.setStorageType(FileServerProperties.TYPE_S3);
|
||||
return fileInfo;
|
||||
} catch (Exception e) {
|
||||
log.error("创建S3文件信息失败: {}", path, e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> listFiles(String prefix) {
|
||||
try {
|
||||
// 使用S3Template获取文件列表
|
||||
// 这里需要根据实际的S3Template方法来实现
|
||||
// 由于S3Template没有直接的listFiles方法,我们使用AmazonS3客户端
|
||||
|
||||
if (s3Template == null) {
|
||||
log.warn("S3Template未配置,无法获取文件列表");
|
||||
return List.of();
|
||||
}
|
||||
|
||||
// 获取AmazonS3客户端
|
||||
com.amazonaws.services.s3.AmazonS3 amazonS3 = s3Template.getAmazonS3();
|
||||
if (amazonS3 == null) {
|
||||
log.warn("AmazonS3客户端未配置,无法获取文件列表");
|
||||
return List.of();
|
||||
}
|
||||
|
||||
// 从配置中获取bucket名称
|
||||
String bucketName = fileServerProperties.getS3().getBucketName();
|
||||
if (bucketName == null || bucketName.isEmpty()) {
|
||||
log.warn("S3 bucket名称未配置,无法获取文件列表");
|
||||
return List.of();
|
||||
}
|
||||
|
||||
// 列出文件
|
||||
com.amazonaws.services.s3.model.ListObjectsV2Request request =
|
||||
new com.amazonaws.services.s3.model.ListObjectsV2Request()
|
||||
.withBucketName(bucketName)
|
||||
.withPrefix(prefix);
|
||||
|
||||
com.amazonaws.services.s3.model.ListObjectsV2Result result = amazonS3.listObjectsV2(request);
|
||||
|
||||
return result.getObjectSummaries().stream()
|
||||
.map(com.amazonaws.services.s3.model.S3ObjectSummary::getKey)
|
||||
.toList();
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("获取S3文件列表失败,前缀: {}", prefix, e);
|
||||
return List.of();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getViewUrlByPathAndExpires(String name, int expires) {
|
||||
try {
|
||||
S3Object s3Object = parsePath(name);
|
||||
return s3Template.getViewUrl(s3Object.bucketName, s3Object.objectName, expires);
|
||||
} catch (Exception e) {
|
||||
log.error("获取S3文件临时URL失败: {}", name, e);
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 从URL下载文件并上传到S3
|
||||
*/
|
||||
public boolean downloadAndUpload(String sourceUrl, String targetPath) {
|
||||
try {
|
||||
S3Object s3Object = parsePath(targetPath);
|
||||
|
||||
// 从URL下载文件
|
||||
URL url = new URL(sourceUrl);
|
||||
|
||||
// 使用HttpURLConnection获取更准确的文件信息
|
||||
java.net.HttpURLConnection connection = (java.net.HttpURLConnection) url.openConnection();
|
||||
connection.setRequestMethod("GET");
|
||||
connection.setConnectTimeout(30000); // 30秒连接超时
|
||||
connection.setReadTimeout(60000); // 60秒读取超时
|
||||
|
||||
int responseCode = connection.getResponseCode();
|
||||
if (responseCode != 200) {
|
||||
log.error("从URL下载文件失败,HTTP状态码: {}, URL: {}", responseCode, sourceUrl);
|
||||
return false;
|
||||
}
|
||||
|
||||
// 获取文件大小和内容类型
|
||||
long contentLength = connection.getContentLengthLong();
|
||||
String contentType = connection.getContentType();
|
||||
if (contentType == null || contentType.isEmpty()) {
|
||||
contentType = "application/octet-stream";
|
||||
}
|
||||
|
||||
log.debug("文件信息 - 大小: {} bytes, 类型: {}, URL: {}", contentLength, contentType, sourceUrl);
|
||||
|
||||
// 使用更安全的方式处理输入流
|
||||
try (InputStream inputStream = connection.getInputStream()) {
|
||||
// 将输入流转换为字节数组,避免流长度问题
|
||||
byte[] fileData = inputStream.readAllBytes();
|
||||
|
||||
if (fileData.length == 0) {
|
||||
log.warn("从URL下载的文件为空: {}", sourceUrl);
|
||||
return false;
|
||||
}
|
||||
|
||||
// 验证文件大小
|
||||
if (contentLength > 0 && fileData.length != contentLength) {
|
||||
log.warn("文件大小不匹配,预期: {}, 实际: {}, URL: {}", contentLength, fileData.length, sourceUrl);
|
||||
}
|
||||
|
||||
// 使用字节数组上传到S3,指定准确的文件大小和内容类型
|
||||
try (InputStream dataInputStream = new java.io.ByteArrayInputStream(fileData)) {
|
||||
// 使用S3Template的私有upload方法,传入准确的大小和内容类型
|
||||
ObjectInfo objectInfo = uploadWithMetadata(s3Object.objectName, dataInputStream, fileData.length, contentType);
|
||||
if (objectInfo != null) {
|
||||
log.info("文件上传成功,源URL: {}, 目标路径: {}, 文件大小: {} bytes",
|
||||
sourceUrl, targetPath, fileData.length);
|
||||
return true;
|
||||
} else {
|
||||
log.error("文件上传失败,返回的ObjectInfo为空");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("下载并上传文件失败,源URL: {}, 目标路径: {}", sourceUrl, targetPath, e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用元数据上传文件到S3
|
||||
*/
|
||||
private ObjectInfo uploadWithMetadata(String objectName, InputStream inputStream, int size, String contentType) {
|
||||
try {
|
||||
// 从配置中获取bucket名称
|
||||
String bucketName = fileServerProperties.getS3().getBucketName();
|
||||
if (bucketName == null || bucketName.isEmpty()) {
|
||||
bucketName = "default-bucket";
|
||||
log.warn("使用默认bucket名称: {}", bucketName);
|
||||
}
|
||||
|
||||
log.debug("使用bucket名称: {} 上传文件: {}", bucketName, objectName);
|
||||
|
||||
// 创建对象元数据
|
||||
com.amazonaws.services.s3.model.ObjectMetadata objectMetadata = new com.amazonaws.services.s3.model.ObjectMetadata();
|
||||
objectMetadata.setContentLength(size);
|
||||
objectMetadata.setContentType(contentType);
|
||||
|
||||
// 创建上传请求
|
||||
com.amazonaws.services.s3.model.PutObjectRequest putObjectRequest = new com.amazonaws.services.s3.model.PutObjectRequest(
|
||||
bucketName, objectName, inputStream, objectMetadata);
|
||||
|
||||
// 设置读取限制
|
||||
putObjectRequest.getRequestClientOptions().setReadLimit(size + 1);
|
||||
|
||||
// 执行上传
|
||||
s3Template.getAmazonS3().putObject(putObjectRequest);
|
||||
|
||||
// 创建返回对象
|
||||
ObjectInfo obj = new ObjectInfo();
|
||||
obj.setObjectPath(bucketName + "/" + objectName);
|
||||
obj.setObjectUrl("s3://" + bucketName + "/" + objectName);
|
||||
return obj;
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("上传文件到S3失败,对象名: {}, 大小: {}", objectName, size, e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查文件是否存在
|
||||
*/
|
||||
public boolean fileExists(String objectPath) {
|
||||
try {
|
||||
S3Object s3Object = parsePath(objectPath);
|
||||
return s3Template.doesObjectExist(s3Object.bucketName, s3Object.objectName);
|
||||
} catch (Exception e) {
|
||||
log.error("检查S3文件是否存在失败: {}", objectPath, e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取文件大小
|
||||
*/
|
||||
public long getFileSize(String objectPath) {
|
||||
try {
|
||||
S3Object s3Object = parsePath(objectPath);
|
||||
Long size = s3Template.getObjectSize(s3Object.bucketName, s3Object.objectName);
|
||||
return size != null ? size : -1;
|
||||
} catch (Exception e) {
|
||||
log.error("获取S3文件大小失败: {}", objectPath, e);
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
private static class S3Object {
|
||||
private String bucketName;
|
||||
private String objectName;
|
||||
}
|
||||
|
||||
private S3Object parsePath(String path) {
|
||||
S3Object s3Object = new S3Object();
|
||||
if (StrUtil.isNotEmpty(path)) {
|
||||
int splitIndex = path.lastIndexOf(CommonConstant.PATH_SPLIT);
|
||||
if (splitIndex != -1) {
|
||||
s3Object.bucketName = path.substring(0, splitIndex);
|
||||
s3Object.objectName = path.substring(splitIndex + 1);
|
||||
} else {
|
||||
// 如果没有分隔符,使用默认bucket
|
||||
s3Object.bucketName = "default-bucket";
|
||||
s3Object.objectName = path;
|
||||
}
|
||||
}
|
||||
return s3Object;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user