Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d488d35fbb |
+7
-64
@@ -5,6 +5,7 @@ import com.alibaba.nacos.shaded.com.google.gson.Gson;
|
|||||||
import com.alibaba.nacos.shaded.com.google.gson.JsonElement;
|
import com.alibaba.nacos.shaded.com.google.gson.JsonElement;
|
||||||
import com.alibaba.nacos.shaded.com.google.gson.JsonObject;
|
import com.alibaba.nacos.shaded.com.google.gson.JsonObject;
|
||||||
import com.central.common.model.Result;
|
import com.central.common.model.Result;
|
||||||
|
import com.central.common.lock.Lock;
|
||||||
import com.central.device.feign.OrderCenterService;
|
import com.central.device.feign.OrderCenterService;
|
||||||
import com.central.device.message.ControlEnum;
|
import com.central.device.message.ControlEnum;
|
||||||
import com.central.device.message.ControlMessageConstant;
|
import com.central.device.message.ControlMessageConstant;
|
||||||
@@ -20,7 +21,6 @@ import io.swagger.v3.oas.annotations.tags.Tag;
|
|||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.beans.factory.annotation.Value;
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
|
||||||
import org.springframework.util.Assert;
|
import org.springframework.util.Assert;
|
||||||
import org.springframework.util.StringUtils;
|
import org.springframework.util.StringUtils;
|
||||||
import org.springframework.web.bind.annotation.*;
|
import org.springframework.web.bind.annotation.*;
|
||||||
@@ -49,9 +49,6 @@ public class ApiDeviceController {
|
|||||||
@Autowired
|
@Autowired
|
||||||
private RequestUtils requestUtils;
|
private RequestUtils requestUtils;
|
||||||
|
|
||||||
@Autowired
|
|
||||||
private StringRedisTemplate redisTemplate;
|
|
||||||
|
|
||||||
private ControlMessageConstant controlMessageConstant = new ControlMessageConstant();
|
private ControlMessageConstant controlMessageConstant = new ControlMessageConstant();
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
@@ -81,6 +78,8 @@ public class ApiDeviceController {
|
|||||||
*/
|
*/
|
||||||
@Operation(summary = "设备属性设置")
|
@Operation(summary = "设备属性设置")
|
||||||
@PostMapping("/setting/{deviceId}/property")
|
@PostMapping("/setting/{deviceId}/property")
|
||||||
|
@Lock(key = "device:writeProperties:#deviceId:#param['order_no']:#param['control']",
|
||||||
|
waitTime = 3, leaseTime = 10, unit = TimeUnit.SECONDS)
|
||||||
public Result writeProperties(@RequestBody Map<String, Object> param, @PathVariable("deviceId") String deviceId) {
|
public Result writeProperties(@RequestBody Map<String, Object> param, @PathVariable("deviceId") String deviceId) {
|
||||||
log.info("开始设置设备属性: deviceId={}, param={}", deviceId, param);
|
log.info("开始设置设备属性: deviceId={}, param={}", deviceId, param);
|
||||||
try {
|
try {
|
||||||
@@ -91,36 +90,23 @@ public class ApiDeviceController {
|
|||||||
return Result.failed("参数错误");
|
return Result.failed("参数错误");
|
||||||
}
|
}
|
||||||
|
|
||||||
// 2. 幂等性检查
|
// 2. 检查订单状态
|
||||||
String idempotencyKey = generateIdempotencyKey(deviceId, orderNo, control);
|
|
||||||
log.info("生成幂等性key: deviceId={}, orderNo={}, control={}, key={}", deviceId, orderNo, control, idempotencyKey);
|
|
||||||
|
|
||||||
if (isRequestProcessed(idempotencyKey)) {
|
|
||||||
log.info("检测到重复请求,返回幂等性响应: deviceId={}, orderNo={}, control={}", deviceId, orderNo, control);
|
|
||||||
return Result.succeed("请求已处理,请勿重复操作");
|
|
||||||
}
|
|
||||||
|
|
||||||
// 3. 立即标记请求已处理(防止并发请求)
|
|
||||||
markRequestAsProcessed(idempotencyKey);
|
|
||||||
log.info("幂等性检查通过,立即标记请求已处理: deviceId={}, orderNo={}, control={}", deviceId, orderNo, control);
|
|
||||||
|
|
||||||
// 4. 检查订单状态
|
|
||||||
String orderStatus = orderCenterService.getOrderStatusByOrderNo(orderNo);
|
String orderStatus = orderCenterService.getOrderStatusByOrderNo(orderNo);
|
||||||
if (!isValidOrderStatus(orderStatus)) {
|
if (!isValidOrderStatus(orderStatus)) {
|
||||||
return Result.failed("设备已处理,请关注订单详情");
|
return Result.failed("设备已处理,请关注订单详情");
|
||||||
}
|
}
|
||||||
|
|
||||||
// 5. 构建控制消息
|
// 3. 构建控制消息
|
||||||
JsonObject controlMessage = buildControlMessage(control, orderNo, deviceId);
|
JsonObject controlMessage = buildControlMessage(control, orderNo, deviceId);
|
||||||
if (controlMessage == null) {
|
if (controlMessage == null) {
|
||||||
return Result.failed("暂未开放控制权限");
|
return Result.failed("暂未开放控制权限");
|
||||||
}
|
}
|
||||||
|
|
||||||
// 6. 发送设备控制请求
|
// 4. 发送设备控制请求
|
||||||
String url = baseUrl + "/device/instance/" + deviceId + "/property";
|
String url = baseUrl + "/device/instance/" + deviceId + "/property";
|
||||||
Map<String, String> result = requestUtils.getPostRequestResultMap(url, controlMessage.toString());
|
Map<String, String> result = requestUtils.getPostRequestResultMap(url, controlMessage.toString());
|
||||||
|
|
||||||
// 7. 处理响应结果
|
// 5. 处理响应结果
|
||||||
return handleDeviceResponse(result, orderNo);
|
return handleDeviceResponse(result, orderNo);
|
||||||
|
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
@@ -323,47 +309,4 @@ public class ApiDeviceController {
|
|||||||
|
|
||||||
return jsonObject;
|
return jsonObject;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* 生成幂等性key
|
|
||||||
*/
|
|
||||||
private String generateIdempotencyKey(String deviceId, String orderNo, String control) {
|
|
||||||
return String.format("device:writeProperties:%s:%s:%s", deviceId, orderNo, control);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 检查请求是否已处理
|
|
||||||
*/
|
|
||||||
private boolean isRequestProcessed(String idempotencyKey) {
|
|
||||||
try {
|
|
||||||
Boolean hasKey = redisTemplate.hasKey(idempotencyKey);
|
|
||||||
log.info("检查幂等性key: key={}, hasKey={}", idempotencyKey, hasKey);
|
|
||||||
|
|
||||||
if (hasKey != null && hasKey) {
|
|
||||||
// 获取key的值进行额外验证
|
|
||||||
String value = redisTemplate.opsForValue().get(idempotencyKey);
|
|
||||||
log.info("幂等性key已存在: key={}, value={}", idempotencyKey, value);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
log.info("幂等性key不存在: key={}", idempotencyKey);
|
|
||||||
return false;
|
|
||||||
} catch (Exception e) {
|
|
||||||
log.error("检查幂等性key异常: key={}, error={}", idempotencyKey, e.getMessage(), e);
|
|
||||||
return false; // Redis异常时不阻止请求
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 标记请求已处理
|
|
||||||
*/
|
|
||||||
private void markRequestAsProcessed(String idempotencyKey) {
|
|
||||||
try {
|
|
||||||
// 设置5分钟过期时间,防止Redis内存占用过多
|
|
||||||
redisTemplate.opsForValue().set(idempotencyKey, "processed", 5, TimeUnit.MINUTES);
|
|
||||||
log.info("标记请求已处理: key={}", idempotencyKey);
|
|
||||||
} catch (Exception e) {
|
|
||||||
log.error("标记幂等性key异常: key={}, error={}", idempotencyKey, e.getMessage(), e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
+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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -15,6 +15,7 @@ import org.springframework.web.bind.annotation.*;
|
|||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
+760
-169
File diff suppressed because it is too large
Load Diff
+119
@@ -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());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+424
@@ -0,0 +1,424 @@
|
|||||||
|
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;
|
||||||
|
import com.central.common.model.Result;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 热数据同步控制器
|
||||||
|
*/
|
||||||
|
@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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 诊断S3配置和URL生成
|
||||||
|
*/
|
||||||
|
@Operation(summary = "诊断S3配置和URL生成")
|
||||||
|
@GetMapping("/diagnose")
|
||||||
|
public Result<Map<String, Object>> diagnoseS3Config() {
|
||||||
|
Map<String, Object> result = new HashMap<>();
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 检查S3配置
|
||||||
|
result.put("s3Enabled", hotDataSyncService.isS3Enabled());
|
||||||
|
result.put("enhancedS3ServiceAvailable", hotDataSyncService.isEnhancedS3ServiceAvailable());
|
||||||
|
result.put("s3ServiceAvailable", hotDataSyncService.isS3ServiceAvailable());
|
||||||
|
|
||||||
|
// 检查S3配置信息
|
||||||
|
result.put("s3Config", hotDataSyncService.getS3ConfigInfo());
|
||||||
|
|
||||||
|
// 测试URL生成
|
||||||
|
result.put("urlTest", hotDataSyncService.testUrlGeneration());
|
||||||
|
|
||||||
|
// 检查热同步配置
|
||||||
|
result.put("hotSyncConfig", hotDataSyncService.getHotSyncConfig());
|
||||||
|
|
||||||
|
// 测试新的S3路径生成
|
||||||
|
Map<String, Object> pathTest = new HashMap<>();
|
||||||
|
pathTest.put("oldPath", "hot-sync/test-file.txt");
|
||||||
|
pathTest.put("newPath", "s3://test-file.txt");
|
||||||
|
result.put("pathTest", pathTest);
|
||||||
|
|
||||||
|
return Result.succeed(result);
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("诊断S3配置失败", e);
|
||||||
|
result.put("error", e.getMessage());
|
||||||
|
return Result.failed("诊断失败:" + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 详细诊断热数据同步问题
|
||||||
|
*/
|
||||||
|
@Operation(summary = "详细诊断热数据同步问题")
|
||||||
|
@GetMapping("/diagnose-detailed")
|
||||||
|
public Result<Map<String, Object>> diagnoseHotSyncDetailed() {
|
||||||
|
Map<String, Object> result = new HashMap<>();
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 1. 检查配置参数
|
||||||
|
Map<String, Object> config = new HashMap<>();
|
||||||
|
config.put("syncEnabled", hotDataSyncService.isRunning());
|
||||||
|
config.put("hotDataDays", 7); // 默认7天
|
||||||
|
config.put("batchSize", 100);
|
||||||
|
config.put("accessThreshold", 10);
|
||||||
|
result.put("config", config);
|
||||||
|
|
||||||
|
// 2. 检查数据库文件统计
|
||||||
|
Map<String, Object> dbStats = new HashMap<>();
|
||||||
|
|
||||||
|
// 这里需要注入FileMapper,暂时用模拟数据
|
||||||
|
dbStats.put("totalFiles", "需要查询数据库");
|
||||||
|
dbStats.put("recentFiles", "需要查询数据库");
|
||||||
|
dbStats.put("ossFiles", "需要查询数据库");
|
||||||
|
dbStats.put("s3Files", "需要查询数据库");
|
||||||
|
result.put("databaseStats", dbStats);
|
||||||
|
|
||||||
|
// 3. 检查OSS服务状态
|
||||||
|
Map<String, Object> ossStatus = new HashMap<>();
|
||||||
|
try {
|
||||||
|
// 这里可以添加OSS服务检查逻辑
|
||||||
|
ossStatus.put("status", "需要检查OSS服务");
|
||||||
|
ossStatus.put("accessible", "需要测试");
|
||||||
|
} catch (Exception e) {
|
||||||
|
ossStatus.put("status", "OSS服务检查失败");
|
||||||
|
ossStatus.put("error", e.getMessage());
|
||||||
|
}
|
||||||
|
result.put("ossStatus", ossStatus);
|
||||||
|
|
||||||
|
// 4. 检查S3服务状态
|
||||||
|
Map<String, Object> s3Status = new HashMap<>();
|
||||||
|
s3Status.put("s3Enabled", hotDataSyncService.isS3Enabled());
|
||||||
|
s3Status.put("enhancedS3ServiceAvailable", hotDataSyncService.isEnhancedS3ServiceAvailable());
|
||||||
|
s3Status.put("s3ServiceAvailable", hotDataSyncService.isS3ServiceAvailable());
|
||||||
|
result.put("s3Status", s3Status);
|
||||||
|
|
||||||
|
// 5. 同步逻辑分析
|
||||||
|
Map<String, Object> syncLogic = new HashMap<>();
|
||||||
|
syncLogic.put("step1", "查询最近7天内的文件");
|
||||||
|
syncLogic.put("step2", "过滤掉已在S3中的文件");
|
||||||
|
syncLogic.put("step3", "过滤掉不在OSS中的文件");
|
||||||
|
syncLogic.put("step4", "剩余文件即为需要同步的文件");
|
||||||
|
result.put("syncLogic", syncLogic);
|
||||||
|
|
||||||
|
// 6. 可能的问题原因
|
||||||
|
Map<String, Object> possibleIssues = new HashMap<>();
|
||||||
|
possibleIssues.put("issue1", "数据库中没有最近7天内的文件");
|
||||||
|
possibleIssues.put("issue2", "所有文件都已经在S3中");
|
||||||
|
possibleIssues.put("issue3", "文件不在OSS中(OSS服务问题)");
|
||||||
|
possibleIssues.put("issue4", "文件存储类型标识不正确");
|
||||||
|
possibleIssues.put("issue5", "OSS/S3服务配置问题");
|
||||||
|
result.put("possibleIssues", possibleIssues);
|
||||||
|
|
||||||
|
// 7. 建议的排查步骤
|
||||||
|
Map<String, Object> troubleshooting = new HashMap<>();
|
||||||
|
troubleshooting.put("step1", "检查数据库中的文件数据");
|
||||||
|
troubleshooting.put("step2", "检查OSS服务是否正常");
|
||||||
|
troubleshooting.put("step3", "检查S3服务是否正常");
|
||||||
|
troubleshooting.put("step4", "检查文件存储类型标识");
|
||||||
|
troubleshooting.put("step5", "手动测试单个文件同步");
|
||||||
|
result.put("troubleshooting", troubleshooting);
|
||||||
|
|
||||||
|
return Result.succeed(result);
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("详细诊断热数据同步失败", e);
|
||||||
|
result.put("error", e.getMessage());
|
||||||
|
return Result.failed("详细诊断失败:" + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 测试URL访问
|
||||||
|
*/
|
||||||
|
@Operation(summary = "测试URL访问")
|
||||||
|
@PostMapping("/test-url")
|
||||||
|
public Result<Map<String, Object>> testUrlAccess(@RequestParam String url) {
|
||||||
|
Map<String, Object> result = new HashMap<>();
|
||||||
|
|
||||||
|
try {
|
||||||
|
log.info("测试URL访问: {}", url);
|
||||||
|
|
||||||
|
// 创建HTTP连接
|
||||||
|
java.net.URL testUrl = new java.net.URL(url);
|
||||||
|
java.net.HttpURLConnection connection = (java.net.HttpURLConnection) testUrl.openConnection();
|
||||||
|
connection.setRequestMethod("GET");
|
||||||
|
connection.setConnectTimeout(10000); // 10秒连接超时
|
||||||
|
connection.setReadTimeout(30000); // 30秒读取超时
|
||||||
|
|
||||||
|
// 设置User-Agent
|
||||||
|
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36");
|
||||||
|
|
||||||
|
int responseCode = connection.getResponseCode();
|
||||||
|
String responseMessage = connection.getResponseMessage();
|
||||||
|
|
||||||
|
result.put("url", url);
|
||||||
|
result.put("responseCode", responseCode);
|
||||||
|
result.put("responseMessage", responseMessage);
|
||||||
|
result.put("contentType", connection.getContentType());
|
||||||
|
result.put("contentLength", connection.getContentLengthLong());
|
||||||
|
result.put("accessible", responseCode == 200);
|
||||||
|
|
||||||
|
// 获取响应头信息
|
||||||
|
Map<String, String> headers = new HashMap<>();
|
||||||
|
connection.getHeaderFields().forEach((key, values) -> {
|
||||||
|
if (key != null && values != null && !values.isEmpty()) {
|
||||||
|
headers.put(key, String.join(", ", values));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
result.put("headers", headers);
|
||||||
|
|
||||||
|
log.info("URL访问测试结果: 状态码={}, 消息={}, 可访问={}", responseCode, responseMessage, responseCode == 200);
|
||||||
|
|
||||||
|
return Result.succeed(result);
|
||||||
|
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("测试URL访问失败: {}", url, e);
|
||||||
|
result.put("url", url);
|
||||||
|
result.put("error", e.getMessage());
|
||||||
|
result.put("accessible", false);
|
||||||
|
return Result.failed("URL访问测试失败:" + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 测试文件同步到S3
|
||||||
|
*/
|
||||||
|
@Operation(summary = "测试文件同步到S3")
|
||||||
|
@PostMapping("/test-sync")
|
||||||
|
public Result<Map<String, Object>> testFileSync(@RequestParam String fileId) {
|
||||||
|
Map<String, Object> result = new HashMap<>();
|
||||||
|
|
||||||
|
try {
|
||||||
|
log.info("测试文件同步到S3: fileId={}", fileId);
|
||||||
|
|
||||||
|
boolean success = hotDataSyncService.syncSpecificFile(fileId);
|
||||||
|
|
||||||
|
result.put("fileId", fileId);
|
||||||
|
result.put("success", success);
|
||||||
|
result.put("message", success ? "文件同步成功" : "文件同步失败");
|
||||||
|
result.put("timestamp", System.currentTimeMillis());
|
||||||
|
|
||||||
|
return Result.succeed(result);
|
||||||
|
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("测试文件同步失败: fileId={}", fileId, e);
|
||||||
|
result.put("fileId", fileId);
|
||||||
|
result.put("error", e.getMessage());
|
||||||
|
result.put("success", false);
|
||||||
|
return Result.failed("文件同步测试失败:" + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 测试URL生成
|
||||||
|
*/
|
||||||
|
@Operation(summary = "测试URL生成")
|
||||||
|
@PostMapping("/test-url-generation")
|
||||||
|
public Result<Map<String, Object>> testUrlGeneration(@RequestParam String path) {
|
||||||
|
Map<String, Object> result = new HashMap<>();
|
||||||
|
|
||||||
|
try {
|
||||||
|
log.info("测试URL生成: path={}", path);
|
||||||
|
|
||||||
|
// 通过HotDataSyncService获取URL生成信息
|
||||||
|
Map<String, Object> urlTest = hotDataSyncService.testUrlGeneration();
|
||||||
|
result.put("path", path);
|
||||||
|
result.put("urlTest", urlTest);
|
||||||
|
result.put("timestamp", System.currentTimeMillis());
|
||||||
|
|
||||||
|
return Result.succeed(result);
|
||||||
|
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("测试URL生成失败: path={}", path, e);
|
||||||
|
result.put("path", path);
|
||||||
|
result.put("error", e.getMessage());
|
||||||
|
return Result.failed("URL生成测试失败:" + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -6,6 +6,7 @@ import com.central.common.model.FileInfo;
|
|||||||
import org.apache.ibatis.annotations.Mapper;
|
import org.apache.ibatis.annotations.Mapper;
|
||||||
import org.apache.ibatis.annotations.Param;
|
import org.apache.ibatis.annotations.Param;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|
||||||
@@ -18,5 +19,32 @@ import java.util.Map;
|
|||||||
public interface FileMapper extends BaseMapper<FileInfo> {
|
public interface FileMapper extends BaseMapper<FileInfo> {
|
||||||
List<FileInfo> findList(Page<FileInfo> page, @Param("params") Map<String, Object> params);
|
List<FileInfo> findList(Page<FileInfo> page, @Param("params") Map<String, Object> params);
|
||||||
|
|
||||||
// 热数据同步相关方法已移除(外部同步)
|
/**
|
||||||
|
* 查询热数据文件列表
|
||||||
|
* 根据时间窗口和存储类型查询需要同步的文件
|
||||||
|
*
|
||||||
|
* @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);
|
||||||
}
|
}
|
||||||
|
|||||||
+263
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
+102
@@ -0,0 +1,102 @@
|
|||||||
|
package com.central.file.service;
|
||||||
|
|
||||||
|
import com.central.common.model.FileInfo;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.context.event.EventListener;
|
||||||
|
import org.springframework.scheduling.annotation.Async;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.time.temporal.ChronoUnit;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 文件同步事件监听器
|
||||||
|
* 监听文件访问事件,自动触发同步
|
||||||
|
*/
|
||||||
|
@Slf4j
|
||||||
|
@Component
|
||||||
|
public class FileSyncEventListener {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private OssToS3SyncService ossToS3SyncService;
|
||||||
|
|
||||||
|
@Value("${zlt.storage.hot-data-days:30}")
|
||||||
|
private int hotDataDays;
|
||||||
|
|
||||||
|
@Value("${zlt.storage.sync.event-driven:true}")
|
||||||
|
private boolean eventDrivenSync; // 是否启用事件驱动同步
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 监听文件访问事件
|
||||||
|
* 当访问冷数据文件时,自动触发同步
|
||||||
|
*/
|
||||||
|
@EventListener
|
||||||
|
@Async
|
||||||
|
public void handleFileAccessEvent(FileAccessEvent event) {
|
||||||
|
if (!eventDrivenSync) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
FileInfo fileInfo = event.getFileInfo();
|
||||||
|
if (fileInfo == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 检查是否为冷数据
|
||||||
|
if (isColdData(fileInfo)) {
|
||||||
|
log.info("检测到冷数据文件访问,触发同步: {}", fileInfo.getPath());
|
||||||
|
|
||||||
|
// 异步同步文件
|
||||||
|
boolean syncResult = ossToS3SyncService.syncFileToS3(fileInfo);
|
||||||
|
if (syncResult) {
|
||||||
|
log.info("事件驱动同步成功: {}", fileInfo.getPath());
|
||||||
|
} else {
|
||||||
|
log.warn("事件驱动同步失败: {}", fileInfo.getPath());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("处理文件访问事件失败", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 检查是否为冷数据
|
||||||
|
*/
|
||||||
|
private boolean isColdData(FileInfo fileInfo) {
|
||||||
|
if (fileInfo.getCreateTime() == null) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
LocalDateTime createTime = fileInfo.getCreateTime().toInstant()
|
||||||
|
.atZone(java.time.ZoneId.systemDefault())
|
||||||
|
.toLocalDateTime();
|
||||||
|
LocalDateTime now = LocalDateTime.now();
|
||||||
|
|
||||||
|
long daysDiff = ChronoUnit.DAYS.between(createTime, now);
|
||||||
|
return daysDiff > hotDataDays;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 文件访问事件
|
||||||
|
*/
|
||||||
|
public static class FileAccessEvent {
|
||||||
|
private final FileInfo fileInfo;
|
||||||
|
private final String accessType; // "READ", "WRITE", "DELETE"
|
||||||
|
|
||||||
|
public FileAccessEvent(FileInfo fileInfo, String accessType) {
|
||||||
|
this.fileInfo = fileInfo;
|
||||||
|
this.accessType = accessType;
|
||||||
|
}
|
||||||
|
|
||||||
|
public FileInfo getFileInfo() {
|
||||||
|
return fileInfo;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getAccessType() {
|
||||||
|
return accessType;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+693
@@ -0,0 +1,693 @@
|
|||||||
|
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;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.HashMap;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 热数据自动同步服务
|
||||||
|
* 负责将热数据自动同步到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路径(不包含hot-sync前缀)
|
||||||
|
String originalPath = getOriginalPath(fileInfo);
|
||||||
|
log.debug("原始OSS路径: {}", originalPath);
|
||||||
|
|
||||||
|
// 从OSS获取文件URL
|
||||||
|
String ossUrl = ossService.getViewUrlByPath(originalPath);
|
||||||
|
if (ossUrl == null || ossUrl.isEmpty()) {
|
||||||
|
log.error("从OSS获取文件URL失败,文件ID: {}, 路径: {}", fileInfo.getId(), originalPath);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
log.debug("获取到OSS文件URL: {}", ossUrl);
|
||||||
|
|
||||||
|
// 生成S3路径
|
||||||
|
String s3Path = generateS3Path(fileInfo);
|
||||||
|
log.debug("生成的S3路径: {}", s3Path);
|
||||||
|
|
||||||
|
// 使用增强的S3服务下载并上传文件
|
||||||
|
boolean uploadSuccess = false;
|
||||||
|
if (enhancedS3Service != null) {
|
||||||
|
log.info("使用增强S3服务同步文件: {} -> {}", ossUrl, s3Path);
|
||||||
|
uploadSuccess = enhancedS3Service.downloadAndUpload(ossUrl, s3Path);
|
||||||
|
} else if (s3Service != null) {
|
||||||
|
// 使用基础S3服务
|
||||||
|
log.warn("使用基础S3服务,功能可能受限");
|
||||||
|
// 这里需要实现具体的上传逻辑
|
||||||
|
uploadSuccess = false; // 暂时设置为false,需要实现具体逻辑
|
||||||
|
} else {
|
||||||
|
log.error("S3服务未配置,无法同步文件");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (uploadSuccess) {
|
||||||
|
// 验证文件是否真的上传成功
|
||||||
|
if (verifyFileUpload(s3Path)) {
|
||||||
|
// 更新文件存储信息
|
||||||
|
updateFileStorageInfo(fileInfo, s3Path);
|
||||||
|
log.info("文件同步成功,文件ID: {}, 新路径: {}", fileInfo.getId(), s3Path);
|
||||||
|
return true;
|
||||||
|
} else {
|
||||||
|
log.error("文件上传验证失败,文件ID: {}", fileInfo.getId());
|
||||||
|
retryCount++;
|
||||||
|
if (retryCount < maxRetries) {
|
||||||
|
log.info("准备重试,等待2秒后重试...");
|
||||||
|
Thread.sleep(2000);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
log.error("文件上传到S3失败,文件ID: {}", fileInfo.getId());
|
||||||
|
retryCount++;
|
||||||
|
if (retryCount < maxRetries) {
|
||||||
|
log.info("准备重试,等待2秒后重试...");
|
||||||
|
Thread.sleep(2000);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
} 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);
|
||||||
|
} 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"))) {
|
||||||
|
log.debug("文件存储类型标识为S3,文件ID: {}", fileInfo.getId());
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 检查路径特征
|
||||||
|
if (fileInfo.getPath() != null) {
|
||||||
|
String path = fileInfo.getPath();
|
||||||
|
|
||||||
|
// 标准S3路径格式
|
||||||
|
if (path.contains("s3://") || path.contains("minio")) {
|
||||||
|
log.debug("文件路径包含S3标识,文件ID: {}", fileInfo.getId());
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 检查是否包含S3存储标识
|
||||||
|
if (path.contains("s3-storage/") || path.contains("cold-storage/")) {
|
||||||
|
log.debug("文件路径包含S3存储标识,文件ID: {}", fileInfo.getId());
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 使用增强S3服务检查文件是否存在
|
||||||
|
if (enhancedS3Service != null && fileInfo.getPath() != null) {
|
||||||
|
try {
|
||||||
|
boolean exists = enhancedS3Service.fileExists(fileInfo.getPath());
|
||||||
|
log.debug("S3服务检查文件存在,文件ID: {}, 存在: {}", fileInfo.getId(), exists);
|
||||||
|
return exists;
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.warn("S3服务检查失败,文件ID: {}, path: {}", fileInfo.getId(), fileInfo.getPath(), e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
log.debug("文件不在S3中,文件ID: {}, path: {}, storageType: {}",
|
||||||
|
fileInfo.getId(), fileInfo.getPath(), fileInfo.getStorageType());
|
||||||
|
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"))) {
|
||||||
|
log.debug("文件存储类型标识为OSS,文件ID: {}", fileInfo.getId());
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 检查路径特征 - 支持多种OSS路径格式
|
||||||
|
if (fileInfo.getPath() != null) {
|
||||||
|
String path = fileInfo.getPath();
|
||||||
|
|
||||||
|
// 标准OSS路径格式
|
||||||
|
if (path.contains("oss://") || path.contains("aliyun")) {
|
||||||
|
log.debug("文件路径包含OSS标识,文件ID: {}", fileInfo.getId());
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 自定义路径格式(如 picture/xxx/xxx)
|
||||||
|
if (path.startsWith("picture/") || path.startsWith("video/") || path.startsWith("file/")) {
|
||||||
|
log.debug("文件路径为自定义格式,文件ID: {}, path: {}", fileInfo.getId(), path);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 尝试从OSS获取URL,如果能获取到说明文件存在
|
||||||
|
if (fileInfo.getPath() != null) {
|
||||||
|
try {
|
||||||
|
String ossUrl = ossService.getViewUrlByPath(fileInfo.getPath());
|
||||||
|
boolean exists = ossUrl != null && !ossUrl.isEmpty();
|
||||||
|
log.debug("OSS服务检查文件存在,文件ID: {}, 存在: {}", fileInfo.getId(), exists);
|
||||||
|
return exists;
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.warn("OSS服务检查失败,文件ID: {}, path: {}", fileInfo.getId(), fileInfo.getPath(), e);
|
||||||
|
// 如果OSS服务检查失败,但路径格式正确,仍然认为是OSS文件
|
||||||
|
if (fileInfo.getPath() != null &&
|
||||||
|
(fileInfo.getPath().startsWith("picture/") ||
|
||||||
|
fileInfo.getPath().startsWith("video/") ||
|
||||||
|
fileInfo.getPath().startsWith("file/"))) {
|
||||||
|
log.debug("OSS服务检查失败,但路径格式正确,认为文件在OSS中,文件ID: {}", fileInfo.getId());
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
log.debug("文件不在OSS中,文件ID: {}, path: {}, storageType: {}",
|
||||||
|
fileInfo.getId(), fileInfo.getPath(), fileInfo.getStorageType());
|
||||||
|
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 "s3://" + fileInfo.getId() + "/" + fileInfo.getName();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 提取文件名,避免路径过长
|
||||||
|
String fileName = fileInfo.getName();
|
||||||
|
if (fileName == null || fileName.isEmpty()) {
|
||||||
|
// 从路径中提取文件名
|
||||||
|
if (originalPath.contains("/")) {
|
||||||
|
fileName = originalPath.substring(originalPath.lastIndexOf("/") + 1);
|
||||||
|
} else {
|
||||||
|
fileName = originalPath;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 生成真正的S3路径,直接使用文件名(不带前缀)
|
||||||
|
return fileName;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取原始OSS路径(去除hot-sync前缀)
|
||||||
|
*/
|
||||||
|
private String getOriginalPath(FileInfo fileInfo) {
|
||||||
|
String path = fileInfo.getPath();
|
||||||
|
if (path == null || path.isEmpty()) {
|
||||||
|
return path;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 如果路径包含hot-sync前缀,去除它
|
||||||
|
if (path.startsWith("hot-sync/")) {
|
||||||
|
return path.substring("hot-sync/".length());
|
||||||
|
}
|
||||||
|
|
||||||
|
return path;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 验证文件是否上传成功
|
||||||
|
*/
|
||||||
|
private boolean verifyFileUpload(String s3Path) {
|
||||||
|
try {
|
||||||
|
if (enhancedS3Service != null) {
|
||||||
|
return enhancedS3Service.fileExists(s3Path);
|
||||||
|
} else if (s3Service != null) {
|
||||||
|
// 基础S3服务验证
|
||||||
|
String url = s3Service.getViewUrlByPath(s3Path);
|
||||||
|
return url != null && !url.isEmpty();
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.warn("验证文件上传失败: {}", s3Path, e);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 更新文件存储信息
|
||||||
|
*/
|
||||||
|
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("热数据同步配置 - 启用: %s, 批次大小: %d, 同步间隔: %d分钟, 访问阈值: %d, 最大线程数: %d, 热数据天数: %d",
|
||||||
|
syncEnabled, batchSize, syncIntervalMinutes, accessThreshold, maxThreads, hotDataDays);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 检查S3是否启用
|
||||||
|
*/
|
||||||
|
public boolean isS3Enabled() {
|
||||||
|
return syncEnabled;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 检查增强S3服务是否可用
|
||||||
|
*/
|
||||||
|
public boolean isEnhancedS3ServiceAvailable() {
|
||||||
|
return enhancedS3Service != null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 检查基础S3服务是否可用
|
||||||
|
*/
|
||||||
|
public boolean isS3ServiceAvailable() {
|
||||||
|
return s3Service != null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取S3配置信息
|
||||||
|
*/
|
||||||
|
public Map<String, Object> getS3ConfigInfo() {
|
||||||
|
Map<String, Object> config = new HashMap<>();
|
||||||
|
|
||||||
|
if (enhancedS3Service != null) {
|
||||||
|
config.put("enhancedS3Service", "可用");
|
||||||
|
// 尝试获取S3配置信息
|
||||||
|
try {
|
||||||
|
// 这里可以添加更多S3配置信息的获取逻辑
|
||||||
|
config.put("s3Template", enhancedS3Service != null ? "已配置" : "未配置");
|
||||||
|
} catch (Exception e) {
|
||||||
|
config.put("s3Template", "配置错误: " + e.getMessage());
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
config.put("enhancedS3Service", "不可用");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (s3Service != null) {
|
||||||
|
config.put("s3Service", "可用");
|
||||||
|
} else {
|
||||||
|
config.put("s3Service", "不可用");
|
||||||
|
}
|
||||||
|
|
||||||
|
return config;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 测试URL生成
|
||||||
|
*/
|
||||||
|
public Map<String, Object> testUrlGeneration() {
|
||||||
|
Map<String, Object> result = new HashMap<>();
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 测试一个示例路径
|
||||||
|
String testPath = "hot-sync/test-file.txt";
|
||||||
|
|
||||||
|
if (enhancedS3Service != null) {
|
||||||
|
String url = enhancedS3Service.getViewUrlByPath(testPath);
|
||||||
|
result.put("enhancedS3Url", url);
|
||||||
|
result.put("enhancedS3UrlValid", url != null && !url.isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
|
if (s3Service != null) {
|
||||||
|
String url = s3Service.getViewUrlByPath(testPath);
|
||||||
|
result.put("s3ServiceUrl", url);
|
||||||
|
result.put("s3ServiceUrlValid", url != null && !url.isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
|
result.put("testPath", testPath);
|
||||||
|
|
||||||
|
} catch (Exception e) {
|
||||||
|
result.put("error", e.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取热同步配置
|
||||||
|
*/
|
||||||
|
public Map<String, Object> getHotSyncConfig() {
|
||||||
|
Map<String, Object> config = new HashMap<>();
|
||||||
|
config.put("syncEnabled", syncEnabled);
|
||||||
|
config.put("batchSize", batchSize);
|
||||||
|
config.put("syncIntervalMinutes", syncIntervalMinutes);
|
||||||
|
config.put("accessThreshold", accessThreshold);
|
||||||
|
config.put("maxThreads", maxThreads);
|
||||||
|
config.put("hotDataDays", hotDataDays);
|
||||||
|
config.put("running", running);
|
||||||
|
config.put("lastSyncTime", lastSyncTime);
|
||||||
|
config.put("totalSyncedFiles", totalSyncedFiles.get());
|
||||||
|
config.put("totalFailedFiles", totalFailedFiles.get());
|
||||||
|
return config;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -39,6 +39,4 @@ public interface IFileService extends IService<FileInfo> {
|
|||||||
List<String> listFiles(String prefix);
|
List<String> listFiles(String prefix);
|
||||||
|
|
||||||
String getViewUrlByPathAndExpires(String name,int expires);
|
String getViewUrlByPathAndExpires(String name,int expires);
|
||||||
|
|
||||||
String getS3UrlByPath(String path);
|
|
||||||
}
|
}
|
||||||
|
|||||||
+307
@@ -0,0 +1,307 @@
|
|||||||
|
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 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.Component;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.time.LocalTime;
|
||||||
|
import java.time.temporal.ChronoUnit;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.concurrent.atomic.AtomicBoolean;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* OSS到MinIO定时同步调度器
|
||||||
|
* 在晚上00:00至6:00持续同步OSS数据到MinIO
|
||||||
|
*/
|
||||||
|
@Slf4j
|
||||||
|
@Component
|
||||||
|
public class OssToMinioSyncScheduler {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private OssToS3SyncService ossToS3SyncService;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private OssService ossService;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private FileMapper fileMapper;
|
||||||
|
|
||||||
|
@Value("${zlt.storage.hot-data-days:30}")
|
||||||
|
private int hotDataDays; // 热数据保留天数
|
||||||
|
|
||||||
|
@Value("${zlt.storage.sync.enabled:true}")
|
||||||
|
private boolean syncEnabled; // 是否启用同步
|
||||||
|
|
||||||
|
@Value("${zlt.storage.sync.batch-size:50}")
|
||||||
|
private int batchSize; // 批量同步大小
|
||||||
|
|
||||||
|
@Value("${zlt.storage.sync.interval:300000}")
|
||||||
|
private long syncInterval; // 同步间隔(毫秒),默认5分钟
|
||||||
|
|
||||||
|
// 同步状态控制
|
||||||
|
private final AtomicBoolean isNightSyncRunning = new AtomicBoolean(false);
|
||||||
|
private LocalDateTime lastSyncTime = null;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 每天晚上00:00启动夜间同步任务
|
||||||
|
*/
|
||||||
|
@Scheduled(cron = "${zlt.storage.sync.night-start:0 0 0 * * ?}")
|
||||||
|
public void startNightSync() {
|
||||||
|
if (!syncEnabled) {
|
||||||
|
log.info("OSS到MinIO同步功能已禁用");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
log.info("启动夜间OSS到MinIO同步任务");
|
||||||
|
isNightSyncRunning.set(true);
|
||||||
|
|
||||||
|
// 启动夜间同步循环
|
||||||
|
new Thread(this::nightSyncLoop, "NightSyncThread").start();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 每天早上6:00停止夜间同步任务
|
||||||
|
*/
|
||||||
|
@Scheduled(cron = "${zlt.storage.sync.night-stop:0 0 6 * * ?}")
|
||||||
|
public void stopNightSync() {
|
||||||
|
log.info("停止夜间OSS到MinIO同步任务");
|
||||||
|
isNightSyncRunning.set(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 夜间同步循环
|
||||||
|
* 在00:00-6:00期间持续同步
|
||||||
|
*/
|
||||||
|
private void nightSyncLoop() {
|
||||||
|
log.info("开始夜间同步循环");
|
||||||
|
|
||||||
|
while (isNightSyncRunning.get()) {
|
||||||
|
try {
|
||||||
|
LocalTime currentTime = LocalTime.now();
|
||||||
|
|
||||||
|
// 检查是否在夜间同步时间窗口内(00:00-6:00)
|
||||||
|
if (currentTime.isAfter(LocalTime.of(0, 0)) &&
|
||||||
|
currentTime.isBefore(LocalTime.of(6, 0))) {
|
||||||
|
|
||||||
|
// 执行同步任务
|
||||||
|
performNightSync();
|
||||||
|
|
||||||
|
// 等待下次同步
|
||||||
|
Thread.sleep(syncInterval);
|
||||||
|
} else {
|
||||||
|
// 不在夜间时间窗口,等待1分钟后再次检查
|
||||||
|
Thread.sleep(60000);
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
log.info("夜间同步循环被中断");
|
||||||
|
Thread.currentThread().interrupt();
|
||||||
|
break;
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("夜间同步循环异常", e);
|
||||||
|
try {
|
||||||
|
Thread.sleep(60000); // 异常后等待1分钟再继续
|
||||||
|
} catch (InterruptedException ie) {
|
||||||
|
Thread.currentThread().interrupt();
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
log.info("夜间同步循环结束");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 执行夜间同步任务
|
||||||
|
*/
|
||||||
|
private void performNightSync() {
|
||||||
|
try {
|
||||||
|
log.info("执行夜间同步任务 - 时间: {}", LocalDateTime.now());
|
||||||
|
|
||||||
|
// 获取需要同步的文件列表
|
||||||
|
List<FileInfo> filesToSync = getFilesToSync();
|
||||||
|
if (filesToSync.isEmpty()) {
|
||||||
|
log.debug("没有需要同步的文件");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
log.info("找到 {} 个文件需要同步", filesToSync.size());
|
||||||
|
|
||||||
|
int successCount = 0;
|
||||||
|
int failCount = 0;
|
||||||
|
int processedCount = 0;
|
||||||
|
|
||||||
|
for (FileInfo fileInfo : filesToSync) {
|
||||||
|
if (!isNightSyncRunning.get()) {
|
||||||
|
log.info("夜间同步被停止,已处理 {} 个文件", processedCount);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
boolean syncResult = ossToS3SyncService.syncFileToS3(fileInfo);
|
||||||
|
if (syncResult) {
|
||||||
|
successCount++;
|
||||||
|
log.debug("文件同步成功: {}", fileInfo.getPath());
|
||||||
|
} else {
|
||||||
|
failCount++;
|
||||||
|
log.warn("文件同步失败: {}", fileInfo.getPath());
|
||||||
|
}
|
||||||
|
|
||||||
|
processedCount++;
|
||||||
|
|
||||||
|
// 控制同步速度,避免对系统造成压力
|
||||||
|
Thread.sleep(200);
|
||||||
|
|
||||||
|
} catch (Exception e) {
|
||||||
|
failCount++;
|
||||||
|
processedCount++;
|
||||||
|
log.error("文件同步异常: {}, error: {}", fileInfo.getPath(), e.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
// 每处理一批文件后暂停一下
|
||||||
|
if (processedCount % batchSize == 0) {
|
||||||
|
log.info("已处理 {} 个文件,成功: {}, 失败: {}", processedCount, successCount, failCount);
|
||||||
|
Thread.sleep(1000); // 暂停1秒
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
lastSyncTime = LocalDateTime.now();
|
||||||
|
log.info("夜间同步任务完成 - 处理: {}, 成功: {}, 失败: {}",
|
||||||
|
processedCount, successCount, failCount);
|
||||||
|
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("夜间同步任务执行失败", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取需要同步的文件列表
|
||||||
|
*/
|
||||||
|
private List<FileInfo> getFilesToSync() {
|
||||||
|
try {
|
||||||
|
// 获取冷数据文件(超过热数据天数的文件)
|
||||||
|
LocalDateTime coldDataThreshold = LocalDateTime.now().minusDays(hotDataDays);
|
||||||
|
log.info("查询冷数据文件,热数据天数: {}, 冷数据阈值: {}", hotDataDays, coldDataThreshold);
|
||||||
|
|
||||||
|
List<FileInfo> filesToSync = queryColdDataFiles(coldDataThreshold);
|
||||||
|
|
||||||
|
log.info("获取到 {} 个文件需要同步", filesToSync.size());
|
||||||
|
|
||||||
|
return filesToSync;
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("获取需要同步的文件列表失败", e);
|
||||||
|
return java.util.Collections.emptyList();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 查询冷数据文件
|
||||||
|
* 查询创建时间早于threshold且不在S3中的文件
|
||||||
|
*/
|
||||||
|
private List<FileInfo> queryColdDataFiles(LocalDateTime threshold) {
|
||||||
|
try {
|
||||||
|
log.debug("查询冷数据文件,截止时间: {}", threshold);
|
||||||
|
|
||||||
|
// 查询创建时间早于threshold的文件
|
||||||
|
List<FileInfo> allFiles = fileMapper.selectList(null);
|
||||||
|
|
||||||
|
// 过滤出冷数据文件(创建时间早于threshold)
|
||||||
|
List<FileInfo> coldFiles = allFiles.stream()
|
||||||
|
.filter(file -> {
|
||||||
|
if (file.getCreateTime() == null) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 转换为LocalDateTime进行比较
|
||||||
|
LocalDateTime createTime = file.getCreateTime().toInstant()
|
||||||
|
.atZone(java.time.ZoneId.systemDefault())
|
||||||
|
.toLocalDateTime();
|
||||||
|
|
||||||
|
return createTime.isBefore(threshold);
|
||||||
|
})
|
||||||
|
.filter(file -> {
|
||||||
|
// 过滤掉已经在S3中的文件
|
||||||
|
if (file.getStorageType() != null &&
|
||||||
|
(file.getStorageType().contains("S3") || file.getStorageType().contains("MINIO"))) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (file.getPath() != null &&
|
||||||
|
(file.getPath().contains("s3://") || file.getPath().contains("minio") ||
|
||||||
|
file.getPath().contains("s3-storage/") || file.getPath().contains("cold-storage/"))) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
})
|
||||||
|
.filter(file -> {
|
||||||
|
// 确保文件在OSS中(支持多种路径格式)
|
||||||
|
if (file.getStorageType() != null &&
|
||||||
|
(file.getStorageType().contains("OSS") || file.getStorageType().contains("ALIYUN"))) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (file.getPath() != null) {
|
||||||
|
String path = file.getPath();
|
||||||
|
if (path.contains("oss://") || path.contains("aliyun") ||
|
||||||
|
path.startsWith("picture/") || path.startsWith("video/") || path.startsWith("file/")) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
})
|
||||||
|
.limit(batchSize * 2) // 限制查询数量
|
||||||
|
.toList();
|
||||||
|
|
||||||
|
log.info("查询到 {} 个冷数据文件需要同步", coldFiles.size());
|
||||||
|
|
||||||
|
// 记录前几个文件的详细信息用于调试
|
||||||
|
if (!coldFiles.isEmpty()) {
|
||||||
|
log.debug("冷数据文件示例:");
|
||||||
|
coldFiles.stream().limit(3).forEach(file ->
|
||||||
|
log.debug("文件ID: {}, 路径: {}, 创建时间: {}, 存储类型: {}",
|
||||||
|
file.getId(), file.getPath(), file.getCreateTime(), file.getStorageType()));
|
||||||
|
}
|
||||||
|
|
||||||
|
return coldFiles;
|
||||||
|
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("查询冷数据文件失败", e);
|
||||||
|
return java.util.Collections.emptyList();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取同步状态
|
||||||
|
*/
|
||||||
|
public String getSyncStatus() {
|
||||||
|
return String.format("夜间同步状态 - 运行中: %s, 最后同步时间: %s, 热数据天数: %d",
|
||||||
|
isNightSyncRunning.get(),
|
||||||
|
lastSyncTime != null ? lastSyncTime.toString() : "未执行",
|
||||||
|
hotDataDays);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 手动启动夜间同步(用于测试)
|
||||||
|
*/
|
||||||
|
public void manualStartNightSync() {
|
||||||
|
log.info("手动启动夜间同步");
|
||||||
|
isNightSyncRunning.set(true);
|
||||||
|
new Thread(this::nightSyncLoop, "ManualNightSyncThread").start();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 手动停止夜间同步
|
||||||
|
*/
|
||||||
|
public void manualStopNightSync() {
|
||||||
|
log.info("手动停止夜间同步");
|
||||||
|
isNightSyncRunning.set(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
+144
@@ -0,0 +1,144 @@
|
|||||||
|
package com.central.file.service;
|
||||||
|
|
||||||
|
import com.central.common.model.FileInfo;
|
||||||
|
import com.central.file.service.impl.EnhancedS3Service;
|
||||||
|
import com.central.file.service.impl.OssService;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.net.HttpURLConnection;
|
||||||
|
import java.net.URL;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* OSS到S3同步服务
|
||||||
|
* 用于将OSS上的文件同步到S3存储
|
||||||
|
*/
|
||||||
|
@Slf4j
|
||||||
|
@Service
|
||||||
|
public class OssToS3SyncService {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private EnhancedS3Service enhancedS3Service;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private OssService ossService;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 同步OSS文件到S3
|
||||||
|
*
|
||||||
|
* @param ossUrl OSS文件URL
|
||||||
|
* @param s3ObjectName S3对象名称
|
||||||
|
* @return 是否同步成功
|
||||||
|
*/
|
||||||
|
public boolean syncOssToS3(String ossUrl, String s3ObjectName) {
|
||||||
|
try {
|
||||||
|
log.info("开始同步OSS文件到S3: {} -> {}", ossUrl, s3ObjectName);
|
||||||
|
|
||||||
|
// 检查S3中是否已存在
|
||||||
|
if (enhancedS3Service.fileExists(s3ObjectName)) {
|
||||||
|
log.info("S3中已存在文件,跳过同步: {}", s3ObjectName);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 从OSS下载文件
|
||||||
|
InputStream inputStream = downloadFromOss(ossUrl);
|
||||||
|
if (inputStream == null) {
|
||||||
|
log.error("从OSS下载文件失败: {}", ossUrl);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 使用现有的downloadAndUpload方法
|
||||||
|
boolean uploadResult = enhancedS3Service.downloadAndUpload(ossUrl, s3ObjectName);
|
||||||
|
if (uploadResult) {
|
||||||
|
log.info("OSS文件同步到S3成功: {} -> {}", ossUrl, s3ObjectName);
|
||||||
|
} else {
|
||||||
|
log.error("OSS文件同步到S3失败: {} -> {}", ossUrl, s3ObjectName);
|
||||||
|
}
|
||||||
|
|
||||||
|
return uploadResult;
|
||||||
|
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("同步OSS文件到S3异常: {} -> {}", ossUrl, s3ObjectName, e);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据文件信息同步到S3
|
||||||
|
*
|
||||||
|
* @param fileInfo 文件信息
|
||||||
|
* @return 是否同步成功
|
||||||
|
*/
|
||||||
|
public boolean syncFileToS3(FileInfo fileInfo) {
|
||||||
|
if (fileInfo == null || fileInfo.getPath() == null) {
|
||||||
|
log.error("文件信息为空,无法同步");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 使用OSS服务获取带签名的URL
|
||||||
|
String ossUrl = ossService.getViewUrlByPath(fileInfo.getPath());
|
||||||
|
if (ossUrl == null || ossUrl.isEmpty()) {
|
||||||
|
log.error("无法获取OSS文件URL: {}", fileInfo.getPath());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
String s3ObjectName = fileInfo.getPath();
|
||||||
|
return syncOssToS3(ossUrl, s3ObjectName);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据文件路径同步到S3
|
||||||
|
*
|
||||||
|
* @param filePath 文件路径
|
||||||
|
* @return 是否同步成功
|
||||||
|
*/
|
||||||
|
public boolean syncFileToS3(String filePath) {
|
||||||
|
if (filePath == null || filePath.isEmpty()) {
|
||||||
|
log.error("文件路径为空,无法同步");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 使用OSS服务获取带签名的URL
|
||||||
|
String ossUrl = ossService.getViewUrlByPath(filePath);
|
||||||
|
if (ossUrl == null || ossUrl.isEmpty()) {
|
||||||
|
log.error("无法获取OSS文件URL: {}", filePath);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
String s3ObjectName = filePath;
|
||||||
|
return syncOssToS3(ossUrl, s3ObjectName);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 从OSS下载文件
|
||||||
|
*
|
||||||
|
* @param ossUrl OSS文件URL
|
||||||
|
* @return 文件输入流
|
||||||
|
*/
|
||||||
|
private InputStream downloadFromOss(String ossUrl) {
|
||||||
|
try {
|
||||||
|
log.debug("从OSS下载文件: {}", ossUrl);
|
||||||
|
|
||||||
|
URL url = new URL(ossUrl);
|
||||||
|
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
|
||||||
|
connection.setRequestMethod("GET");
|
||||||
|
connection.setConnectTimeout(30000);
|
||||||
|
connection.setReadTimeout(30000);
|
||||||
|
|
||||||
|
int responseCode = connection.getResponseCode();
|
||||||
|
if (responseCode == 200) {
|
||||||
|
log.debug("OSS文件下载成功: {}", ossUrl);
|
||||||
|
return connection.getInputStream();
|
||||||
|
} else {
|
||||||
|
log.error("OSS文件下载失败,响应码: {}, URL: {}", responseCode, ossUrl);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("从OSS下载文件异常: {}", ossUrl, e);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+171
-247
@@ -1,11 +1,9 @@
|
|||||||
package com.central.file.service;
|
package com.central.file.service;
|
||||||
|
|
||||||
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
|
||||||
import com.central.common.model.FileInfo;
|
import com.central.common.model.FileInfo;
|
||||||
import com.central.file.mapper.FileMapper;
|
|
||||||
import com.central.file.service.impl.EnhancedS3Service;
|
|
||||||
import com.central.file.service.impl.OssService;
|
import com.central.file.service.impl.OssService;
|
||||||
import com.central.file.service.impl.S3Service;
|
import com.central.file.service.impl.S3Service;
|
||||||
|
import com.central.file.service.impl.EnhancedS3Service;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.beans.factory.annotation.Qualifier;
|
import org.springframework.beans.factory.annotation.Qualifier;
|
||||||
@@ -18,8 +16,10 @@ import java.time.temporal.ChronoUnit;
|
|||||||
/**
|
/**
|
||||||
* 时间窗口智能存储服务
|
* 时间窗口智能存储服务
|
||||||
* 根据文件创建时间自动选择存储位置:
|
* 根据文件创建时间自动选择存储位置:
|
||||||
* - 热数据(阈值天数内):OSS
|
* - 热数据(30天内):存储在OSS,访问速度快
|
||||||
* - 冷数据(超过阈值天数):MinIO(S3)
|
* - 冷数据(30天后):迁移到MinIO,降低成本
|
||||||
|
*
|
||||||
|
* @author system
|
||||||
*/
|
*/
|
||||||
@Slf4j
|
@Slf4j
|
||||||
@Service
|
@Service
|
||||||
@@ -36,63 +36,42 @@ public class TimeWindowStorageService {
|
|||||||
@Qualifier("enhancedS3FileService")
|
@Qualifier("enhancedS3FileService")
|
||||||
private EnhancedS3Service enhancedS3Service;
|
private EnhancedS3Service enhancedS3Service;
|
||||||
|
|
||||||
@Autowired
|
@Autowired(required = false)
|
||||||
private FileMapper fileMapper;
|
private OssToS3SyncService ossToS3SyncService;
|
||||||
|
|
||||||
// 配置参数(时间阈值与开关,默认启用基于时间的路由)
|
// 配置参数
|
||||||
@Value("${zlt.storage.time-router.days:90}")
|
@Value("${zlt.storage.hot-data-days:30}")
|
||||||
private int hotDataDays; // 热数据保留天数(小于等于该天数走OSS,大于该天数走MinIO)
|
private int hotDataDays; // 热数据保留天数,默认30天
|
||||||
|
|
||||||
@Value("${zlt.storage.time-router.enabled:true}")
|
@Value("${zlt.storage.enable-time-window:true}")
|
||||||
private boolean enableTimeWindow; // 是否启用时间窗口存储
|
private boolean enableTimeWindow; // 是否启用时间窗口存储
|
||||||
|
|
||||||
@Value("${cdn.oss.domain:cdn.goflytec.com}")
|
|
||||||
private String ossCdnDomain;
|
|
||||||
|
|
||||||
@Value("${cdn.s3.domain:minicdn.goflytec.com}")
|
|
||||||
private String s3CdnDomain;
|
|
||||||
|
|
||||||
@Value("${cdn.s3.enabled:true}")
|
|
||||||
private boolean enableCdn;
|
|
||||||
|
|
||||||
private final String OSS_DOMAIN = "goflyapp.oss-cn-beijing.aliyuncs.com";
|
|
||||||
private final String S3_DOMAIN = "220.205.16.27:9000";
|
|
||||||
|
|
||||||
final String OSS_DOMAIN_PREFIX = "https://goflyapp.oss-cn-beijing.aliyuncs.com/";
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 智能获取文件访问URL(通过ID)
|
* 智能获取文件访问URL
|
||||||
|
* 根据文件创建时间自动选择存储位置
|
||||||
|
*
|
||||||
|
* @param fileId 文件ID
|
||||||
|
* @return 访问URL
|
||||||
*/
|
*/
|
||||||
public String getSmartViewUrl(String fileId) {
|
public String getSmartViewUrl(String fileId) {
|
||||||
try {
|
try {
|
||||||
|
// 1. 获取文件信息
|
||||||
FileInfo fileInfo = ossService.getFileInfo(fileId);
|
FileInfo fileInfo = ossService.getFileInfo(fileId);
|
||||||
if (fileInfo == null) {
|
if (fileInfo == null) {
|
||||||
log.warn("文件不存在: fileId={}", fileId);
|
log.warn("文件不存在: fileId={}", fileId);
|
||||||
return "";
|
return "";
|
||||||
}
|
}
|
||||||
String storageType = getStorageTypeByTime(fileInfo);
|
|
||||||
log.info("时间窗口判定: fileId={} createTime={} hotDataDays={} enableTimeWindow={} -> storageType={}",
|
|
||||||
fileInfo.getId(), fileInfo.getCreateTime(), hotDataDays, enableTimeWindow, storageType);
|
|
||||||
|
|
||||||
return getViewUrlByStorageType(fileInfo, storageType);
|
// 2. 判断存储类型
|
||||||
} catch (Exception e) {
|
|
||||||
log.error("智能存储查询失败: fileId={}, error={}", fileId, e.getMessage(), e);
|
|
||||||
return "";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 智能获取文件访问URL(通过ID)
|
|
||||||
*/
|
|
||||||
public String getSmartZipViewUrl(String fileId, String style) {
|
|
||||||
try {
|
|
||||||
FileInfo fileInfo = ossService.getFileInfo(fileId);
|
|
||||||
if (fileInfo == null) {
|
|
||||||
log.warn("文件不存在: fileId={}", fileId);
|
|
||||||
return "";
|
|
||||||
}
|
|
||||||
String storageType = getStorageTypeByTime(fileInfo);
|
String storageType = getStorageTypeByTime(fileInfo);
|
||||||
return getZipViewUrlByStorageType(fileInfo, storageType, style);
|
|
||||||
|
// 3. 根据存储类型获取URL
|
||||||
|
String viewUrl = getViewUrlByStorageType(fileInfo, storageType);
|
||||||
|
|
||||||
|
log.info("智能存储查询成功: fileId={}, storageType={}, url={}",
|
||||||
|
fileId, storageType, viewUrl);
|
||||||
|
|
||||||
|
return viewUrl;
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.error("智能存储查询失败: fileId={}, error={}", fileId, e.getMessage(), e);
|
log.error("智能存储查询失败: fileId={}, error={}", fileId, e.getMessage(), e);
|
||||||
return "";
|
return "";
|
||||||
@@ -101,76 +80,28 @@ public class TimeWindowStorageService {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* 智能获取文件访问URL(通过路径)
|
* 智能获取文件访问URL(通过路径)
|
||||||
|
*
|
||||||
|
* @param filePath 文件路径
|
||||||
|
* @return 访问URL
|
||||||
*/
|
*/
|
||||||
public String getSmartViewUrlByPath(String filePath) {
|
public String getSmartViewUrlByPath(String filePath) {
|
||||||
try {
|
try {
|
||||||
FileInfo fileInfo = getFileInfoByPath(filePath);
|
// 1. 根据路径特征判断存储类型
|
||||||
if (fileInfo != null) {
|
if (isS3Path(filePath)) {
|
||||||
String storageType = getStorageTypeByTime(fileInfo);
|
log.debug("S3路径,直接查询S3: path={}", filePath);
|
||||||
log.info("[PATH] 时间窗口判定: path={} createTime={} hotDataDays={} enableTimeWindow={} -> storageType={}",
|
return queryFromS3ByPath(filePath);
|
||||||
filePath, fileInfo.getCreateTime(), hotDataDays, enableTimeWindow, storageType);
|
} else if (isOssPath(filePath)) {
|
||||||
String url = getViewUrlByStorageType(fileInfo, storageType);
|
log.debug("OSS路径,直接查询OSS: path={}", filePath);
|
||||||
log.info("[PATH] 按时间窗口获取URL: path={} storageType={} url={}", filePath, storageType, url);
|
return ossService.getViewUrlByPath(filePath);
|
||||||
return url;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// DB无记录
|
// 2. 路径特征不明确,尝试智能查询
|
||||||
if (!enableTimeWindow) {
|
log.debug("路径特征不明确,尝试智能查询: path={}", filePath);
|
||||||
log.warn("[PATH] 数据库未找到文件信息,时间路由关闭,直接从OSS获取: path={}", filePath);
|
return getViewUrlByFallback(filePath);
|
||||||
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());
|
|
||||||
}
|
|
||||||
log.warn("路径查询失败(OSS未命中): path={}", filePath);
|
|
||||||
return "";
|
|
||||||
} else {
|
|
||||||
log.warn("[PATH] 数据库未找到文件信息,时间路由开启,按冷优先策略查询: path={}", filePath);
|
|
||||||
String s3Url = queryFromS3ByPath(filePath);
|
|
||||||
if (s3Url != null && !s3Url.isEmpty()) {
|
|
||||||
log.debug("S3查询成功: path={}", filePath);
|
|
||||||
return s3Url;
|
|
||||||
}
|
|
||||||
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());
|
|
||||||
}
|
|
||||||
log.warn("路径查询失败(OSS/S3均未命中): path={}", filePath);
|
|
||||||
return "";
|
|
||||||
}
|
|
||||||
} catch (Exception e) {
|
|
||||||
log.error("智能存储路径查询异常: path={}, error={}", filePath, e.getMessage(), e);
|
|
||||||
return "";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private FileInfo getFileInfoByPath(String filePath) {
|
} catch (Exception e) {
|
||||||
try {
|
log.error("智能存储查询失败: path={}, error={}", filePath, e.getMessage(), e);
|
||||||
if (filePath == null || filePath.isEmpty()) {
|
return "";
|
||||||
return null;
|
|
||||||
}
|
|
||||||
QueryWrapper<FileInfo> wrapper = new QueryWrapper<>();
|
|
||||||
wrapper.eq("path", filePath).last("limit 1");
|
|
||||||
FileInfo info = fileMapper.selectOne(wrapper);
|
|
||||||
if (info == null) {
|
|
||||||
// 某些历史数据可能用 name 作为相对路径,兼容一下
|
|
||||||
wrapper = new QueryWrapper<>();
|
|
||||||
wrapper.eq("name", filePath).last("limit 1");
|
|
||||||
info = fileMapper.selectOne(wrapper);
|
|
||||||
}
|
|
||||||
return info;
|
|
||||||
} catch (Exception ex) {
|
|
||||||
log.warn("按路径查询文件信息异常: path={}, error={}", filePath, ex.getMessage());
|
|
||||||
return null;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -179,24 +110,30 @@ public class TimeWindowStorageService {
|
|||||||
*/
|
*/
|
||||||
private String getStorageTypeByTime(FileInfo fileInfo) {
|
private String getStorageTypeByTime(FileInfo fileInfo) {
|
||||||
if (!enableTimeWindow) {
|
if (!enableTimeWindow) {
|
||||||
return "OSS";
|
// 时间窗口功能关闭,使用默认OSS存储
|
||||||
}
|
|
||||||
if (fileInfo.getCreateTime() == null) {
|
|
||||||
log.warn("文件创建时间为空,默认使用OSS: fileId={}", fileInfo.getId());
|
|
||||||
return "OSS";
|
return "OSS";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (fileInfo.getCreateTime() == null) {
|
||||||
|
log.warn("文件创建时间为空,使用默认OSS存储: fileId={}", fileInfo.getId());
|
||||||
|
return "OSS";
|
||||||
|
}
|
||||||
|
|
||||||
|
// 计算文件创建时间距离现在的天数
|
||||||
LocalDateTime createTime = fileInfo.getCreateTime().toInstant()
|
LocalDateTime createTime = fileInfo.getCreateTime().toInstant()
|
||||||
.atZone(java.time.ZoneId.systemDefault())
|
.atZone(java.time.ZoneId.systemDefault())
|
||||||
.toLocalDateTime();
|
.toLocalDateTime();
|
||||||
LocalDateTime now = LocalDateTime.now();
|
LocalDateTime now = LocalDateTime.now();
|
||||||
|
|
||||||
long daysDiff = ChronoUnit.DAYS.between(createTime, now);
|
long daysDiff = ChronoUnit.DAYS.between(createTime, now);
|
||||||
|
|
||||||
if (daysDiff <= hotDataDays) {
|
if (daysDiff <= hotDataDays) {
|
||||||
log.info("热数据,使用OSS: fileId={}, daysDiff={}", fileInfo.getId(), daysDiff);
|
// 热数据,使用OSS
|
||||||
|
log.debug("热数据,使用OSS存储: fileId={}, daysDiff={}", fileInfo.getId(), daysDiff);
|
||||||
return "OSS";
|
return "OSS";
|
||||||
} else {
|
} else {
|
||||||
log.info("冷数据,使用S3: fileId={}, daysDiff={}", fileInfo.getId(), daysDiff);
|
// 冷数据,使用S3(MinIO)
|
||||||
|
log.debug("冷数据,使用S3存储: fileId={}, daysDiff={}", fileInfo.getId(), daysDiff);
|
||||||
return "S3";
|
return "S3";
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -205,76 +142,32 @@ public class TimeWindowStorageService {
|
|||||||
* 根据存储类型获取访问URL
|
* 根据存储类型获取访问URL
|
||||||
*/
|
*/
|
||||||
private String getViewUrlByStorageType(FileInfo fileInfo, String storageType) {
|
private String getViewUrlByStorageType(FileInfo fileInfo, String storageType) {
|
||||||
log.info("根据存储类型获取URL: fileId={}, storageType={}",
|
log.info("根据存储类型获取URL: fileId={}, storageType={}, path={}",
|
||||||
fileInfo.getId(), storageType);
|
fileInfo.getId(), storageType, fileInfo.getPath());
|
||||||
|
|
||||||
if ("S3".equals(storageType)) {
|
if ("S3".equals(storageType)) {
|
||||||
// 冷数据:S3优先,失败降级到OSS
|
// 冷数据,优先从S3查询
|
||||||
String s3Url = queryUrlFromS3(fileInfo);
|
log.info("冷数据,优先从S3查询: fileId={}", fileInfo.getId());
|
||||||
|
String s3Url = queryFromS3(fileInfo);
|
||||||
if (s3Url != null && !s3Url.isEmpty()) {
|
if (s3Url != null && !s3Url.isEmpty()) {
|
||||||
return applyCdnAcceleration(s3Url, "S3");
|
log.info("S3查询成功: fileId={}, url={}", fileInfo.getId(), s3Url);
|
||||||
}
|
|
||||||
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 = queryUrlFromS3(fileInfo);
|
|
||||||
return applyCdnAcceleration(s3Url, "S3");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private String getZipViewUrlByStorageType(FileInfo fileInfo, String storageType, String style) {
|
|
||||||
if ("S3".equals(storageType)) {
|
|
||||||
// 冷数据:S3优先,失败降级到OSS
|
|
||||||
String s3Url = queryUrlFromS3(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 {
|
|
||||||
String normalized = fileInfo.getPath().startsWith(OSS_DOMAIN_PREFIX) ? fileInfo.getPath().substring(OSS_DOMAIN_PREFIX.length()) : fileInfo.getPath();
|
|
||||||
String ossZipUrl = ossService.getZipViewUrlByPath(normalized, style);
|
|
||||||
if (ossZipUrl != null && !ossZipUrl.isEmpty()) {
|
|
||||||
log.info("OSS查询成功: fileId={}, url={}", fileInfo.getId(), ossZipUrl);
|
|
||||||
return ossZipUrl;
|
|
||||||
}
|
|
||||||
log.warn("OSS查询失败,降级到S3: fileId={}", fileInfo.getId());
|
|
||||||
String s3Url = queryUrlFromS3(fileInfo);
|
|
||||||
log.info("S3降级查询结果: fileId={}, url={}", fileInfo.getId(), s3Url);
|
|
||||||
return s3Url;
|
return s3Url;
|
||||||
}
|
}
|
||||||
|
// S3查询失败,降级到OSS
|
||||||
|
log.warn("S3查询失败,降级到OSS: fileId={}", fileInfo.getId());
|
||||||
|
return queryFromOss(fileInfo);
|
||||||
|
} else {
|
||||||
|
// 热数据,优先从OSS查询
|
||||||
|
log.info("热数据,优先从OSS查询: fileId={}", fileInfo.getId());
|
||||||
|
String ossUrl = queryFromOss(fileInfo);
|
||||||
|
if (ossUrl != null && !ossUrl.isEmpty()) {
|
||||||
|
log.info("OSS查询成功: fileId={}, url={}", fileInfo.getId(), ossUrl);
|
||||||
|
return ossUrl;
|
||||||
}
|
}
|
||||||
|
// OSS查询失败,降级到S3
|
||||||
public String applyCdnAcceleration(String originalUrl, String storageType) {
|
log.warn("OSS查询失败,降级到S3: fileId={}", fileInfo.getId());
|
||||||
if (originalUrl == null || originalUrl.isEmpty()) {
|
return queryFromS3(fileInfo);
|
||||||
return originalUrl;
|
|
||||||
}
|
}
|
||||||
if(!enableCdn){
|
|
||||||
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;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -282,17 +175,11 @@ public class TimeWindowStorageService {
|
|||||||
*/
|
*/
|
||||||
private String queryFromOss(FileInfo fileInfo) {
|
private String queryFromOss(FileInfo fileInfo) {
|
||||||
try {
|
try {
|
||||||
String path = fileInfo.getPath();
|
return ossService.getViewUrlByPath(fileInfo.getPath());
|
||||||
if (path != null && !path.isEmpty()) {
|
|
||||||
// 一键成片可能保存完整 OSS URL,这里去掉域名前缀转为相对路径
|
|
||||||
String normalized = path.startsWith(OSS_DOMAIN_PREFIX) ? path.substring(OSS_DOMAIN_PREFIX.length()) : path;
|
|
||||||
return ossService.getViewUrlByPath(normalized);
|
|
||||||
}
|
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.warn("从OSS查询失败: fileId={}, error={}", fileInfo.getId(), e.getMessage());
|
log.warn("从OSS查询失败: fileId={}, error={}", fileInfo.getId(), e.getMessage());
|
||||||
return "";
|
return "";
|
||||||
}
|
}
|
||||||
return "";
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -300,65 +187,21 @@ public class TimeWindowStorageService {
|
|||||||
*/
|
*/
|
||||||
private String queryFromS3(FileInfo fileInfo) {
|
private String queryFromS3(FileInfo fileInfo) {
|
||||||
try {
|
try {
|
||||||
String path = fileInfo.getPath();
|
// 优先使用EnhancedS3Service
|
||||||
if (path != null && !path.isEmpty()) {
|
|
||||||
// 一键成片可能保存完整 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;
|
|
||||||
|
|
||||||
if (enhancedS3Service != null) {
|
if (enhancedS3Service != null) {
|
||||||
log.debug("使用EnhancedS3Service查询: fileId={}, path={}", fileInfo.getId(), normalized);
|
log.debug("使用EnhancedS3Service查询: fileId={}, path={}", fileInfo.getId(), fileInfo.getPath());
|
||||||
String url = enhancedS3Service.getViewUrlByPath(normalized);
|
return enhancedS3Service.getViewUrlByPath(fileInfo.getPath());
|
||||||
if (url == null || url.isEmpty()) {
|
|
||||||
log.warn("从S3查询为空(Enhanced): fileId={} path={}", fileInfo.getId(), normalized);
|
|
||||||
} else {
|
|
||||||
log.debug("从S3获取URL(Enhanced): fileId={} url={}", fileInfo.getId(), url);
|
|
||||||
}
|
|
||||||
return url;
|
|
||||||
} else if (s3Service != null) {
|
} else if (s3Service != null) {
|
||||||
log.debug("使用S3Service查询: fileId={}, path={}", fileInfo.getId(), normalized);
|
log.debug("使用S3Service查询: fileId={}, path={}", fileInfo.getId(), fileInfo.getPath());
|
||||||
String url = s3Service.getViewUrlByPath(normalized);
|
return s3Service.getViewUrlByPath(fileInfo.getPath());
|
||||||
if (url == null || url.isEmpty()) {
|
|
||||||
log.warn("从S3查询为空(基础): fileId={} path={}", fileInfo.getId(), normalized);
|
|
||||||
} else {
|
|
||||||
log.debug("从S3获取URL(基础): fileId={} url={}", fileInfo.getId(), url);
|
|
||||||
}
|
|
||||||
return url;
|
|
||||||
} else {
|
} else {
|
||||||
log.warn("S3服务未配置,无法查询S3: fileId={}", fileInfo.getId());
|
log.warn("S3服务未配置,无法查询S3: fileId={}", fileInfo.getId());
|
||||||
return "";
|
return "";
|
||||||
}
|
}
|
||||||
}
|
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.warn("从S3查询失败: fileId={}, error={}", fileInfo.getId(), e.getMessage());
|
log.warn("从S3查询失败: fileId={}, error={}", fileInfo.getId(), e.getMessage());
|
||||||
return "";
|
return "";
|
||||||
}
|
}
|
||||||
return "";
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
private String queryUrlFromS3(FileInfo fileInfo) {
|
|
||||||
try {
|
|
||||||
String path = fileInfo.getPath();
|
|
||||||
if (path != null && !path.isEmpty()) {
|
|
||||||
// 一键成片可能保存完整 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;
|
|
||||||
if(s3Service != null) {
|
|
||||||
log.debug("使用S3Service查询: fileId={}, path={}", fileInfo.getId(), normalized);
|
|
||||||
String url = s3Service.getS3UrlByPath(normalized);
|
|
||||||
log.info("从s3获取到的路径为:{}",url);
|
|
||||||
return url;
|
|
||||||
} else {
|
|
||||||
log.warn("S3服务未配置,无法查询S3: fileId={}", fileInfo.getId());
|
|
||||||
return "";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (Exception e) {
|
|
||||||
log.warn("从S3查询失败: fileId={}, error={}", fileInfo.getId(), e.getMessage());
|
|
||||||
return "";
|
|
||||||
}
|
|
||||||
return "";
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -366,17 +209,29 @@ public class TimeWindowStorageService {
|
|||||||
*/
|
*/
|
||||||
private String queryFromS3ByPath(String filePath) {
|
private String queryFromS3ByPath(String filePath) {
|
||||||
try {
|
try {
|
||||||
// 一键成片可能保存完整 OSS URL,这里去掉域名前缀转为相对路径
|
// 优先使用EnhancedS3Service
|
||||||
final String OSS_DOMAIN_PREFIX = "https://goflyapp.oss-cn-beijing.aliyuncs.com/";
|
|
||||||
String normalized = filePath.startsWith(OSS_DOMAIN_PREFIX) ? filePath.substring(OSS_DOMAIN_PREFIX.length()) : filePath;
|
|
||||||
if (enhancedS3Service != null) {
|
if (enhancedS3Service != null) {
|
||||||
log.debug("使用EnhancedS3Service查询: path={}", normalized);
|
log.debug("使用EnhancedS3Service查询: path={}", filePath);
|
||||||
return enhancedS3Service.getViewUrlByPath(normalized);
|
String s3Url = enhancedS3Service.getViewUrlByPath(filePath);
|
||||||
} else if (s3Service != null) {
|
|
||||||
log.debug("使用S3Service查询: path={}", normalized);
|
// 如果S3中没有找到文件,尝试从OSS同步
|
||||||
return s3Service.getViewUrlByPath(normalized);
|
if ((s3Url == null || s3Url.isEmpty()) && ossToS3SyncService != null) {
|
||||||
|
log.info("S3中未找到文件,尝试从OSS同步: path={}", filePath);
|
||||||
|
boolean syncResult = ossToS3SyncService.syncFileToS3(filePath);
|
||||||
|
if (syncResult) {
|
||||||
|
log.info("OSS同步到S3成功,重新获取URL: path={}", filePath);
|
||||||
|
s3Url = enhancedS3Service.getViewUrlByPath(filePath);
|
||||||
} else {
|
} else {
|
||||||
log.warn("S3服务未配置,无法查询S3: path={}", normalized);
|
log.warn("OSS同步到S3失败: path={}", filePath);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return s3Url;
|
||||||
|
} else if (s3Service != null) {
|
||||||
|
log.debug("使用S3Service查询: path={}", filePath);
|
||||||
|
return s3Service.getViewUrlByPath(filePath);
|
||||||
|
} else {
|
||||||
|
log.warn("S3服务未配置,无法查询S3: path={}", filePath);
|
||||||
return "";
|
return "";
|
||||||
}
|
}
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
@@ -386,26 +241,96 @@ public class TimeWindowStorageService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 检查文件是否需要迁移(当前仅用于判断,未触发自动迁移)
|
* 降级查询策略
|
||||||
|
*/
|
||||||
|
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.startsWith("s3://") ||
|
||||||
|
path.contains("minio") ||
|
||||||
|
path.startsWith("cold-storage") ||
|
||||||
|
path.contains("S3") ||
|
||||||
|
path.startsWith("hot-sync/") || // 兼容旧的hot-sync前缀
|
||||||
|
// 只有明确包含S3标识的路径才认为是S3路径
|
||||||
|
path.contains("s3://") ||
|
||||||
|
path.contains("minio://")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 判断是否为OSS路径
|
||||||
|
*/
|
||||||
|
private boolean isOssPath(String path) {
|
||||||
|
return path != null && (
|
||||||
|
path.startsWith("oss://") ||
|
||||||
|
path.contains("aliyun") ||
|
||||||
|
path.contains("ali-oss") ||
|
||||||
|
path.contains("OSS") ||
|
||||||
|
path.startsWith("https://goflyapp.oss-cn-beijing.aliyuncs.com/")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 检查文件是否需要迁移
|
||||||
|
*
|
||||||
|
* @param fileInfo 文件信息
|
||||||
|
* @return 是否需要迁移
|
||||||
*/
|
*/
|
||||||
public boolean needMigration(FileInfo fileInfo) {
|
public boolean needMigration(FileInfo fileInfo) {
|
||||||
if (!enableTimeWindow) {
|
if (!enableTimeWindow) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
String storageType = getStorageTypeByTime(fileInfo);
|
String storageType = getStorageTypeByTime(fileInfo);
|
||||||
return "S3".equals(storageType) && !isFileInS3(fileInfo);
|
return "S3".equals(storageType) && !isFileInS3(fileInfo);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 检查文件是否已在S3中
|
||||||
|
*/
|
||||||
private boolean isFileInS3(FileInfo fileInfo) {
|
private boolean isFileInS3(FileInfo fileInfo) {
|
||||||
try {
|
try {
|
||||||
|
// 检查存储类型
|
||||||
if (fileInfo.getStorageType() != null &&
|
if (fileInfo.getStorageType() != null &&
|
||||||
(fileInfo.getStorageType().contains("S3") || fileInfo.getStorageType().contains("MINIO"))) {
|
(fileInfo.getStorageType().contains("S3") || fileInfo.getStorageType().contains("MINIO"))) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 检查路径特征
|
||||||
if (fileInfo.getPath() != null &&
|
if (fileInfo.getPath() != null &&
|
||||||
(fileInfo.getPath().contains("s3://") || fileInfo.getPath().contains("minio"))) {
|
(fileInfo.getPath().contains("s3://") || fileInfo.getPath().contains("minio"))) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.warn("检查文件S3状态失败: fileId={}", fileInfo.getId(), e);
|
log.warn("检查文件S3状态失败: fileId={}", fileInfo.getId(), e);
|
||||||
@@ -422,4 +347,3 @@ public class TimeWindowStorageService {
|
|||||||
hotDataDays, enableTimeWindow, s3Status);
|
hotDataDays, enableTimeWindow, s3Status);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -98,11 +98,6 @@ public class CosService extends AbstractIFileService {
|
|||||||
return "";
|
return "";
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
|
||||||
public String getS3UrlByPath(String path) {
|
|
||||||
return "";
|
|
||||||
}
|
|
||||||
|
|
||||||
private COSObject parsePath(String path) {
|
private COSObject parsePath(String path) {
|
||||||
COSObject cosObject = new COSObject();
|
COSObject cosObject = new COSObject();
|
||||||
if (StrUtil.isNotEmpty(path)) {
|
if (StrUtil.isNotEmpty(path)) {
|
||||||
|
|||||||
+24
-31
@@ -1,6 +1,7 @@
|
|||||||
package com.central.file.service.impl;
|
package com.central.file.service.impl;
|
||||||
|
|
||||||
import cn.hutool.core.util.StrUtil;
|
import cn.hutool.core.util.StrUtil;
|
||||||
|
import com.central.common.constant.CommonConstant;
|
||||||
import com.central.common.model.FileInfo;
|
import com.central.common.model.FileInfo;
|
||||||
import com.central.oss.model.ObjectInfo;
|
import com.central.oss.model.ObjectInfo;
|
||||||
import com.central.oss.properties.FileServerProperties;
|
import com.central.oss.properties.FileServerProperties;
|
||||||
@@ -68,18 +69,17 @@ public class EnhancedS3Service extends AbstractIFileService {
|
|||||||
try {
|
try {
|
||||||
S3Object s3Object = parsePath(name);
|
S3Object s3Object = parsePath(name);
|
||||||
log.info("解析S3路径: {} -> bucket: {}, object: {}", name, s3Object.bucketName, s3Object.objectName);
|
log.info("解析S3路径: {} -> bucket: {}, object: {}", name, s3Object.bucketName, s3Object.objectName);
|
||||||
// 打印未签名的S3完整访问路径(endpoint/bucket/object)
|
|
||||||
try {
|
// 检查文件是否存在
|
||||||
String endpoint = fileServerProperties.getS3().getEndpoint();
|
boolean exists = s3Template.doesObjectExist(s3Object.bucketName, s3Object.objectName);
|
||||||
if (endpoint != null && !endpoint.isEmpty()) {
|
log.info("S3文件存在检查: bucket={}, object={}, exists={}", s3Object.bucketName, s3Object.objectName, exists);
|
||||||
String normalizedEndpoint = endpoint.endsWith("/") ? endpoint.substring(0, endpoint.length() - 1) : endpoint;
|
|
||||||
String rawUrl = normalizedEndpoint + "/" + s3Object.bucketName + "/" + s3Object.objectName;
|
if (!exists) {
|
||||||
log.info("S3访问完整路径(未签名): {}", rawUrl);
|
log.warn("S3文件不存在: bucket={}, object={}", s3Object.bucketName, s3Object.objectName);
|
||||||
}
|
return "";
|
||||||
} catch (Exception ignore) {
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 直接生成预签名URL,避免额外的HEAD存在性检查引发的握手问题
|
// 使用getViewUrl方法获取预签名URL
|
||||||
String url = s3Template.getViewUrl(s3Object.bucketName, s3Object.objectName, 60); // 60分钟有效期
|
String url = s3Template.getViewUrl(s3Object.bucketName, s3Object.objectName, 60); // 60分钟有效期
|
||||||
log.info("生成S3 URL: {}", url);
|
log.info("生成S3 URL: {}", url);
|
||||||
return url;
|
return url;
|
||||||
@@ -194,11 +194,6 @@ public class EnhancedS3Service extends AbstractIFileService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
|
||||||
public String getS3UrlByPath(String path) {
|
|
||||||
return "";
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 从URL下载文件并上传到S3
|
* 从URL下载文件并上传到S3
|
||||||
*/
|
*/
|
||||||
@@ -341,7 +336,7 @@ public class EnhancedS3Service extends AbstractIFileService {
|
|||||||
private S3Object parsePath(String path) {
|
private S3Object parsePath(String path) {
|
||||||
S3Object s3Object = new S3Object();
|
S3Object s3Object = new S3Object();
|
||||||
if (StrUtil.isNotEmpty(path)) {
|
if (StrUtil.isNotEmpty(path)) {
|
||||||
// 1) 显式 s3://bucket/object 格式
|
// 处理s3://bucket/object格式
|
||||||
if (path.startsWith("s3://")) {
|
if (path.startsWith("s3://")) {
|
||||||
String[] parts = path.substring(5).split("/", 2);
|
String[] parts = path.substring(5).split("/", 2);
|
||||||
if (parts.length >= 2) {
|
if (parts.length >= 2) {
|
||||||
@@ -351,25 +346,23 @@ public class EnhancedS3Service extends AbstractIFileService {
|
|||||||
s3Object.bucketName = fileServerProperties.getS3().getBucketName();
|
s3Object.bucketName = fileServerProperties.getS3().getBucketName();
|
||||||
s3Object.objectName = decodeUrl(parts[0]);
|
s3Object.objectName = decodeUrl(parts[0]);
|
||||||
}
|
}
|
||||||
return s3Object;
|
} else if (path.startsWith("hot-sync/")) {
|
||||||
}
|
// 处理hot-sync前缀的路径(兼容旧格式)
|
||||||
|
|
||||||
// 2) 兼容历史 hot-sync/ 前缀:对象名去掉前缀,bucket 用配置
|
|
||||||
if (path.startsWith("hot-sync/")) {
|
|
||||||
s3Object.bucketName = fileServerProperties.getS3().getBucketName();
|
s3Object.bucketName = fileServerProperties.getS3().getBucketName();
|
||||||
s3Object.objectName = decodeUrl(path.substring("hot-sync/".length()));
|
s3Object.objectName = decodeUrl(path.substring("hot-sync/".length())); // 去掉hot-sync/前缀并解码
|
||||||
return s3Object;
|
} else {
|
||||||
}
|
// 处理相对路径或无前缀路径
|
||||||
|
int splitIndex = path.lastIndexOf(CommonConstant.PATH_SPLIT);
|
||||||
// 3) 统一相对路径策略:bucket 固定取配置,objectName 使用完整 path
|
if (splitIndex != -1) {
|
||||||
// 这样与 OSS 目录保持一致:同一个 filePath 在 S3 作为对象键
|
s3Object.bucketName = path.substring(0, splitIndex);
|
||||||
|
s3Object.objectName = decodeUrl(path.substring(splitIndex + 1));
|
||||||
|
} else {
|
||||||
|
// 如果没有分隔符,使用配置的bucket
|
||||||
s3Object.bucketName = fileServerProperties.getS3().getBucketName();
|
s3Object.bucketName = fileServerProperties.getS3().getBucketName();
|
||||||
s3Object.objectName = decodeUrl(path);
|
s3Object.objectName = decodeUrl(path);
|
||||||
return s3Object;
|
|
||||||
}
|
}
|
||||||
// path 为空时,退回配置 bucket,空对象名
|
}
|
||||||
s3Object.bucketName = fileServerProperties.getS3().getBucketName();
|
}
|
||||||
s3Object.objectName = "";
|
|
||||||
return s3Object;
|
return s3Object;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+1
-6
@@ -21,7 +21,7 @@ import java.util.List;
|
|||||||
* Github: https://github.com/zlt2000
|
* Github: https://github.com/zlt2000
|
||||||
*/
|
*/
|
||||||
@Service
|
@Service
|
||||||
@ConditionalOnProperty(prefix = FileServerProperties.PREFIX, name = "type", havingValue = FileServerProperties.TYPE_FDFS)
|
@ConditionalOnProperty(prefix = com.central.oss.properties.FileServerProperties.PREFIX, name = "type", havingValue = FileServerProperties.TYPE_FDFS)
|
||||||
public class FastdfsService extends AbstractIFileService {
|
public class FastdfsService extends AbstractIFileService {
|
||||||
@Resource
|
@Resource
|
||||||
private FdfsTemplate fdfsTemplate;
|
private FdfsTemplate fdfsTemplate;
|
||||||
@@ -84,9 +84,4 @@ public class FastdfsService extends AbstractIFileService {
|
|||||||
public String getViewUrlByPathAndExpires(String name, int expires) {
|
public String getViewUrlByPathAndExpires(String name, int expires) {
|
||||||
return "";
|
return "";
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
|
||||||
public String getS3UrlByPath(String path) {
|
|
||||||
return "";
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -148,11 +148,6 @@ public class OssService extends AbstractIFileService {
|
|||||||
return ossTemplate.getViewUrl(name,expires);
|
return ossTemplate.getViewUrl(name,expires);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
|
||||||
public String getS3UrlByPath(String path) {
|
|
||||||
return "";
|
|
||||||
}
|
|
||||||
|
|
||||||
private OSSObject parsePath(String path) {
|
private OSSObject parsePath(String path) {
|
||||||
OSSObject ossObject = new OSSObject();
|
OSSObject ossObject = new OSSObject();
|
||||||
if (StrUtil.isNotEmpty(path)) {
|
if (StrUtil.isNotEmpty(path)) {
|
||||||
|
|||||||
@@ -145,15 +145,6 @@ public class S3Service extends AbstractIFileService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
|
||||||
public String getS3UrlByPath(String path) {
|
|
||||||
try {
|
|
||||||
return s3Template.getViewUrlNoExpires(path);
|
|
||||||
} catch (Exception e) {
|
|
||||||
return "";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Setter
|
@Setter
|
||||||
@Getter
|
@Getter
|
||||||
private class S3Object {
|
private class S3Object {
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package com.central.file.utils;
|
|||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.springframework.util.StringUtils;
|
import org.springframework.util.StringUtils;
|
||||||
|
|
||||||
|
import java.net.URL;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.regex.Pattern;
|
import java.util.regex.Pattern;
|
||||||
|
|||||||
@@ -0,0 +1,36 @@
|
|||||||
|
# OSS到MinIO同步配置
|
||||||
|
zlt:
|
||||||
|
storage:
|
||||||
|
# 热数据保留天数
|
||||||
|
hot-data-days: 30
|
||||||
|
|
||||||
|
# 同步功能配置
|
||||||
|
sync:
|
||||||
|
# 是否启用同步
|
||||||
|
enabled: true
|
||||||
|
|
||||||
|
# 夜间同步配置
|
||||||
|
night-start: "0 0 0 * * ?" # 每天晚上00:00启动
|
||||||
|
night-stop: "0 0 6 * * ?" # 每天早上6:00停止
|
||||||
|
|
||||||
|
# 同步间隔(毫秒)
|
||||||
|
interval: 180000 # 3分钟
|
||||||
|
|
||||||
|
# 批量同步大小
|
||||||
|
batch-size: 100
|
||||||
|
|
||||||
|
# 是否启用事件驱动同步
|
||||||
|
event-driven: true
|
||||||
|
|
||||||
|
# 同步线程池配置
|
||||||
|
thread-pool:
|
||||||
|
core-size: 2
|
||||||
|
max-size: 5
|
||||||
|
queue-size: 100
|
||||||
|
keep-alive: 60
|
||||||
|
|
||||||
|
# 日志配置
|
||||||
|
logging:
|
||||||
|
level:
|
||||||
|
com.central.file.service.OssToMinioSyncScheduler: INFO
|
||||||
|
com.central.file.service.OssToS3SyncService: DEBUG
|
||||||
@@ -28,7 +28,7 @@ zlt:
|
|||||||
file-server:
|
file-server:
|
||||||
type: oss # 主存储类型(用于文件上传)
|
type: oss # 主存储类型(用于文件上传)
|
||||||
s3:
|
s3:
|
||||||
enabled: true
|
enabled: true # 启用S3服务(用于冷数据存储)
|
||||||
access-key: ${zlt.s3.access-key}
|
access-key: ${zlt.s3.access-key}
|
||||||
accessKeySecret: ${zlt.s3.accessKeySecret}
|
accessKeySecret: ${zlt.s3.accessKeySecret}
|
||||||
endpoint: ${zlt.s3.endpoint}
|
endpoint: ${zlt.s3.endpoint}
|
||||||
@@ -45,12 +45,27 @@ zlt:
|
|||||||
secretKey: ${zlt.oss.secretKey}
|
secretKey: ${zlt.oss.secretKey}
|
||||||
endpoint: ${zlt.oss.endpoint}
|
endpoint: ${zlt.oss.endpoint}
|
||||||
bucketName: ${zlt.oss.bucketName}
|
bucketName: ${zlt.oss.bucketName}
|
||||||
|
# 时间窗口存储配置
|
||||||
storage:
|
storage:
|
||||||
time-router:
|
enable-time-window: true # 启用时间窗口智能存储
|
||||||
# 开启按时间路由
|
hot-data-days: 30 # 热数据保留天数
|
||||||
enabled: true
|
migration:
|
||||||
# 阈值天数;<=90 天走 OSS,>90 天走 MinIO
|
enable-verification: true # 启用迁移验证
|
||||||
days: 30
|
delete-source: false # 迁移后是否删除源文件
|
||||||
|
batch-size: 100 # 迁移批次大小
|
||||||
|
hot-sync:
|
||||||
|
enabled: true # 启用热数据同步
|
||||||
|
batch-size: 100 # 批次大小
|
||||||
|
interval-minutes: 30 # 同步间隔
|
||||||
|
access-threshold: 10 # 访问次数阈值
|
||||||
|
max-threads: 5 # 最大线程数
|
||||||
|
|
||||||
|
sync:
|
||||||
|
schedule:
|
||||||
|
enabled: true # 启用定时任务
|
||||||
|
cron: "0 0 2 * * ?" # 每日同步时间
|
||||||
|
status-check:
|
||||||
|
cron: "0 0 * * * ?" # 状态检查时间
|
||||||
#多租户配置
|
#多租户配置
|
||||||
tenant:
|
tenant:
|
||||||
enable: false
|
enable: false
|
||||||
@@ -78,12 +93,6 @@ aliyun:
|
|||||||
default-batch-size: 100
|
default-batch-size: 100
|
||||||
# 任务等待超时时间(秒)
|
# 任务等待超时时间(秒)
|
||||||
task-timeout: 300
|
task-timeout: 300
|
||||||
cdn:
|
|
||||||
enabled: true
|
|
||||||
oss:
|
|
||||||
domain: cdn.goflytec.com
|
|
||||||
s3:
|
|
||||||
domain: minicdn.goflytec.com
|
|
||||||
|
|
||||||
# 日志配置
|
# 日志配置
|
||||||
logging:
|
logging:
|
||||||
|
|||||||
@@ -50,6 +50,34 @@
|
|||||||
ORDER BY createTime DESC
|
ORDER BY createTime DESC
|
||||||
</select>
|
</select>
|
||||||
|
|
||||||
<!-- 热数据同步相关查询已移除(外部同步) -->
|
<!-- 查询热数据文件列表 -->
|
||||||
|
<select id="selectHotDataFiles" resultType="com.central.common.model.FileInfo">
|
||||||
|
SELECT * FROM file_info
|
||||||
|
WHERE create_time >= #{hotDataThreshold}
|
||||||
|
AND size > 0
|
||||||
|
AND (storage_type IS NULL OR storage_type NOT LIKE '%S3%' OR storage_type NOT LIKE '%MINIO%')
|
||||||
|
AND (path IS NULL OR path NOT LIKE '%s3://%' OR path NOT LIKE '%minio%')
|
||||||
|
ORDER BY create_time DESC
|
||||||
|
LIMIT #{limit}
|
||||||
|
</select>
|
||||||
|
|
||||||
|
<!-- 根据存储类型查询文件 -->
|
||||||
|
<select id="selectFilesByStorageType" resultType="com.central.common.model.FileInfo">
|
||||||
|
SELECT * FROM file_info
|
||||||
|
WHERE storage_type = #{storageType}
|
||||||
|
AND size > 0
|
||||||
|
ORDER BY create_time DESC
|
||||||
|
LIMIT #{limit}
|
||||||
|
</select>
|
||||||
|
|
||||||
|
<!-- 查询需要同步的文件(不在S3中的OSS文件) -->
|
||||||
|
<select id="selectFilesNeedSync" resultType="com.central.common.model.FileInfo">
|
||||||
|
SELECT * FROM file_info
|
||||||
|
WHERE (storage_type IS NULL OR storage_type NOT LIKE '%S3%' OR storage_type NOT LIKE '%MINIO%')
|
||||||
|
AND (path IS NULL OR path NOT LIKE '%s3://%' OR path NOT LIKE '%minio%')
|
||||||
|
AND size > 0
|
||||||
|
ORDER BY create_time DESC
|
||||||
|
LIMIT #{limit}
|
||||||
|
</select>
|
||||||
|
|
||||||
</mapper>
|
</mapper>
|
||||||
|
|||||||
+7
-287
@@ -714,7 +714,7 @@ public class OrderController {
|
|||||||
.toList();
|
.toList();
|
||||||
String aiVideoUrl = null;
|
String aiVideoUrl = null;
|
||||||
if (!aiVideoFiles.isEmpty()) {
|
if (!aiVideoFiles.isEmpty()) {
|
||||||
aiVideoUrl = fileCenterService.getFileViewUrl(aiVideoFiles.get(0).getFileId());
|
aiVideoUrl = fileCenterService.getViewUrlByPath(aiVideoFiles.get(0).getFilePath()).replace(cdnOssUrl, cdnUrl);
|
||||||
}
|
}
|
||||||
orderFileMap.put("aiVideo", aiVideoUrl);
|
orderFileMap.put("aiVideo", aiVideoUrl);
|
||||||
|
|
||||||
@@ -727,11 +727,11 @@ public class OrderController {
|
|||||||
fileMap.put("style", fileStyle);
|
fileMap.put("style", fileStyle);
|
||||||
for (OrderFile orderFile : imgFiles){
|
for (OrderFile orderFile : imgFiles){
|
||||||
Map<String,String> imgMap = new HashMap<>();
|
Map<String,String> imgMap = new HashMap<>();
|
||||||
String url = fileCenterService.getFileViewUrl(orderFile.getFileId());
|
String url = fileCenterService.getViewUrlByPath(orderFile.getFilePath());
|
||||||
imgMap.put("url", url);
|
imgMap.put("url", url.replace(cdnOssUrl, cdnUrl));
|
||||||
imgMap.put("contentType", orderFile.getFileType());
|
imgMap.put("contentType", orderFile.getFileType());
|
||||||
imgMap.put("path", orderFile.getFilePath());
|
imgMap.put("path", orderFile.getFilePath());
|
||||||
fileMap.put("fileId",orderFile.getFileId());
|
fileMap.put("path",orderFile.getFilePath());
|
||||||
imgMap.put("viewUrl", fileCenterService.getViewUrlByPathStyle(fileMap));
|
imgMap.put("viewUrl", fileCenterService.getViewUrlByPathStyle(fileMap));
|
||||||
imgList.add(imgMap);
|
imgList.add(imgMap);
|
||||||
}
|
}
|
||||||
@@ -745,8 +745,8 @@ public class OrderController {
|
|||||||
for (int i = 0; i < videoFiles.size(); i++){
|
for (int i = 0; i < videoFiles.size(); i++){
|
||||||
OrderFile orderFile = videoFiles.get(i);
|
OrderFile orderFile = videoFiles.get(i);
|
||||||
Map<String,String> videoMap = new HashMap<>();
|
Map<String,String> videoMap = new HashMap<>();
|
||||||
String url = fileCenterService.getFileViewUrl(orderFile.getFileId());
|
String url = fileCenterService.getViewUrlByPath(orderFile.getFilePath());
|
||||||
videoMap.put("url", url);
|
videoMap.put("url", url.replace(cdnOssUrl, cdnUrl));
|
||||||
videoMap.put("contentType", orderFile.getFileType());
|
videoMap.put("contentType", orderFile.getFileType());
|
||||||
videoMap.put("path", orderFile.getFilePath());
|
videoMap.put("path", orderFile.getFilePath());
|
||||||
|
|
||||||
@@ -866,7 +866,7 @@ public class OrderController {
|
|||||||
/**
|
/**
|
||||||
* 新版:查询用户订单详情列表(含视频/图片/一键成片)- 性能优化版本
|
* 新版:查询用户订单详情列表(含视频/图片/一键成片)- 性能优化版本
|
||||||
*/
|
*/
|
||||||
/*@Operation(summary = "新版-查询用户订单详情列表(含视频/图片/一键成片)")
|
@Operation(summary = "新版-查询用户订单详情列表(含视频/图片/一键成片)")
|
||||||
@Parameters({
|
@Parameters({
|
||||||
@Parameter(name = "page",description = "分页起始位置",required = true,in=ParameterIn.QUERY),
|
@Parameter(name = "page",description = "分页起始位置",required = true,in=ParameterIn.QUERY),
|
||||||
@Parameter(name = "limit",description = "分页结束位置",required = true,in=ParameterIn.QUERY)
|
@Parameter(name = "limit",description = "分页结束位置",required = true,in=ParameterIn.QUERY)
|
||||||
@@ -1019,286 +1019,6 @@ public class OrderController {
|
|||||||
return PageResult.<Map>builder().data(page).resp_code(0).count(result.getCount()).build();
|
return PageResult.<Map>builder().data(page).resp_code(0).count(result.getCount()).build();
|
||||||
}
|
}
|
||||||
return new PageResult<>();
|
return new PageResult<>();
|
||||||
}*/
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 优化版:查询用户订单详情列表(含视频/图片/一键成片)
|
|
||||||
* 重构版本,提高代码可读性和维护性
|
|
||||||
*/
|
|
||||||
@Operation(summary = "优化版-查询用户订单详情列表(含视频/图片/一键成片)")
|
|
||||||
@Parameters({
|
|
||||||
@Parameter(name = "page",description = "分页起始位置",required = true,in=ParameterIn.QUERY),
|
|
||||||
@Parameter(name = "limit",description = "分页结束位置",required = true,in=ParameterIn.QUERY)
|
|
||||||
})
|
|
||||||
@GetMapping("/user/v2")
|
|
||||||
public PageResult<Map> listInfoByUserV3(@RequestParam Map<String, Object> params) {
|
|
||||||
// 1. 准备查询参数
|
|
||||||
LoginAppUser user = LoginUserContextHolder.getUser();
|
|
||||||
params.put("userId", user.getId());
|
|
||||||
params.put("orderStatusList", getCompletedOrderStatuses());
|
|
||||||
|
|
||||||
// 2. 查询订单数据
|
|
||||||
PageResult<Order> orderResult = orderService.findListByUser(params);
|
|
||||||
if (orderResult.getCount() == 0) {
|
|
||||||
return new PageResult<>();
|
|
||||||
}
|
|
||||||
|
|
||||||
// 3. 批量加载所需数据
|
|
||||||
BatchLoadedData batchData = batchLoadOrderRelatedData(orderResult.getData());
|
|
||||||
|
|
||||||
// 4. 构建返回结果
|
|
||||||
List<Map> resultList = buildOrderDetailList(orderResult.getData(), batchData);
|
|
||||||
|
|
||||||
return PageResult.<Map>builder()
|
|
||||||
.data(resultList)
|
|
||||||
.resp_code(0)
|
|
||||||
.count(orderResult.getCount())
|
|
||||||
.build();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 批量加载订单相关数据的内部类
|
|
||||||
*/
|
|
||||||
private static class BatchLoadedData {
|
|
||||||
Map<String, List<OrderFile>> orderFilesMap;
|
|
||||||
Map<Long, Tourism> tourismMap;
|
|
||||||
Map<String, QrCode> qrCodeMap;
|
|
||||||
Map<String, String> fileUrlMap;
|
|
||||||
Map<String, String> fileStyleUrlMap;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 获取已完成的订单状态列表
|
|
||||||
*/
|
|
||||||
private List<Integer> getCompletedOrderStatuses() {
|
|
||||||
return List.of(
|
|
||||||
OrderStatus.COMPLETE.getId(),
|
|
||||||
OrderStatus.UPLOADING.getId(),
|
|
||||||
OrderStatus.UPLOADED.getId()
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 批量加载订单相关的所有数据
|
|
||||||
*/
|
|
||||||
private BatchLoadedData batchLoadOrderRelatedData(List<Order> orders) {
|
|
||||||
BatchLoadedData data = new BatchLoadedData();
|
|
||||||
|
|
||||||
// 1. 提取所有ID
|
|
||||||
List<String> orderNos = orders.stream()
|
|
||||||
.map(Order::getOrderNo)
|
|
||||||
.collect(Collectors.toList());
|
|
||||||
|
|
||||||
Set<Long> tourismIds = orders.stream()
|
|
||||||
.map(Order::getTourismId)
|
|
||||||
.collect(Collectors.toSet());
|
|
||||||
|
|
||||||
List<String> codeIds = orders.stream()
|
|
||||||
.map(Order::getCodeId)
|
|
||||||
.collect(Collectors.toList());
|
|
||||||
|
|
||||||
// 2. 批量查询数据
|
|
||||||
data.orderFilesMap = orderFileService.getOrderFilesByOrderNos(orderNos);
|
|
||||||
data.tourismMap = tourismService.getTourismsByIds(tourismIds);
|
|
||||||
data.qrCodeMap = qrCodeService.getByCodeIds(codeIds).stream()
|
|
||||||
.collect(Collectors.toMap(QrCode::getCodeId, qrCode -> qrCode));
|
|
||||||
|
|
||||||
// 3. 批量处理文件URL
|
|
||||||
loadFileUrls(data);
|
|
||||||
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 批量加载文件URL和样式URL
|
|
||||||
*/
|
|
||||||
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<>();
|
|
||||||
data.fileStyleUrlMap = new HashMap<>();
|
|
||||||
|
|
||||||
// 批量获取文件URL
|
|
||||||
for (String fileId : allFileIds) {
|
|
||||||
String url = fileCenterService.getFileViewUrl(fileId);
|
|
||||||
if(url!=null && !url.isEmpty()){
|
|
||||||
data.fileUrlMap.put(fileId, url);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 为图片文件生成样式URL
|
|
||||||
for (List<OrderFile> files : data.orderFilesMap.values()) {
|
|
||||||
for (OrderFile file : files) {
|
|
||||||
if (isImageFile(file.getFileType())) {
|
|
||||||
Map<String, String> styleParams = new HashMap<>();
|
|
||||||
styleParams.put("fileId", file.getFileId());
|
|
||||||
styleParams.put("style", fileStyle);
|
|
||||||
String styleUrl = fileCenterService.getViewUrlByPathStyle(styleParams);
|
|
||||||
data.fileStyleUrlMap.put(file.getFileId(), styleUrl);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 构建订单详情列表
|
|
||||||
*/
|
|
||||||
private List<Map> buildOrderDetailList(List<Order> orders, BatchLoadedData batchData) {
|
|
||||||
List<Map> resultList = new ArrayList<>();
|
|
||||||
|
|
||||||
for (Order order : orders) {
|
|
||||||
Map<String, Object> orderDetail = buildSingleOrderDetail(order, batchData);
|
|
||||||
resultList.add(orderDetail);
|
|
||||||
}
|
|
||||||
|
|
||||||
return resultList;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 构建单个订单的详情
|
|
||||||
*/
|
|
||||||
private Map<String, Object> buildSingleOrderDetail(Order order, BatchLoadedData batchData) {
|
|
||||||
Map<String, Object> detail = new HashMap<>();
|
|
||||||
|
|
||||||
// 1. 基本信息
|
|
||||||
detail.put("time", sdf.format(order.getCreateTime()));
|
|
||||||
detail.put("orderNo", order.getOrderNo());
|
|
||||||
detail.put("orderStatus", order.getOrderStatus());
|
|
||||||
|
|
||||||
// 2. 景区信息
|
|
||||||
Tourism tourism = batchData.tourismMap.get(order.getTourismId());
|
|
||||||
detail.put("addr", tourism != null ? tourism.getTourismAddress() : "");
|
|
||||||
|
|
||||||
// 3. 二维码配置
|
|
||||||
QrCode qrCode = batchData.qrCodeMap.get(order.getCodeId());
|
|
||||||
Integer showVideoEditOnly = qrCode != null ? qrCode.getShowVideoEditOnly() : 1;
|
|
||||||
detail.put("showVideoEditOnly", showVideoEditOnly);
|
|
||||||
|
|
||||||
// 4. 文件信息
|
|
||||||
List<OrderFile> orderFiles = batchData.orderFilesMap.getOrDefault(order.getOrderNo(), new ArrayList<>());
|
|
||||||
|
|
||||||
// 5. 处理AI视频
|
|
||||||
String aiVideoUrl = extractAiVideoUrl(orderFiles, batchData.fileUrlMap);
|
|
||||||
detail.put("aiVideo", aiVideoUrl);
|
|
||||||
|
|
||||||
// 6. 根据配置决定是否返回素材
|
|
||||||
if (shouldShowMediaFiles(showVideoEditOnly)) {
|
|
||||||
detail.put("imgList", buildImageList(orderFiles, batchData));
|
|
||||||
detail.put("videoList", buildVideoList(orderFiles, batchData, detail));
|
|
||||||
} else {
|
|
||||||
detail.put("imgList", new ArrayList<>());
|
|
||||||
detail.put("videoList", new ArrayList<>());
|
|
||||||
}
|
|
||||||
|
|
||||||
return detail;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 提取AI视频URL
|
|
||||||
*/
|
|
||||||
private String extractAiVideoUrl(List<OrderFile> files, Map<String, String> fileUrlMap) {
|
|
||||||
return files.stream()
|
|
||||||
.filter(f -> "ai_video".equals(f.getFileTag()))
|
|
||||||
.findFirst()
|
|
||||||
.map(f -> fileUrlMap.get(f.getFileId()))
|
|
||||||
.orElse(null);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 判断是否应该显示媒体文件
|
|
||||||
*/
|
|
||||||
private boolean shouldShowMediaFiles(Integer showVideoEditOnly) {
|
|
||||||
return showVideoEditOnly != null && showVideoEditOnly != 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 构建图片列表
|
|
||||||
*/
|
|
||||||
private List<Map<String, String>> buildImageList(List<OrderFile> files, BatchLoadedData batchData) {
|
|
||||||
List<Map<String, String>> imageList = new ArrayList<>();
|
|
||||||
|
|
||||||
List<OrderFile> imageFiles = files.stream()
|
|
||||||
.filter(f -> "image/jpeg".equals(f.getFileType()))
|
|
||||||
.toList();
|
|
||||||
|
|
||||||
for (OrderFile file : imageFiles) {
|
|
||||||
Map<String, String> imageInfo = new HashMap<>();
|
|
||||||
imageInfo.put("url", batchData.fileUrlMap.get(file.getFileId()));
|
|
||||||
imageInfo.put("contentType", file.getFileType());
|
|
||||||
imageInfo.put("path", file.getFilePath());
|
|
||||||
|
|
||||||
// 生成样式URL
|
|
||||||
Map<String, String> styleParams = new HashMap<>();
|
|
||||||
styleParams.put("fileId", file.getFileId());
|
|
||||||
styleParams.put("style", fileStyle);
|
|
||||||
imageInfo.put("viewUrl", fileCenterService.getViewUrlByPathStyle(styleParams));
|
|
||||||
|
|
||||||
imageList.add(imageInfo);
|
|
||||||
}
|
|
||||||
|
|
||||||
return imageList;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 构建视频列表
|
|
||||||
*/
|
|
||||||
private List<Map<String, String>> buildVideoList(List<OrderFile> files,
|
|
||||||
BatchLoadedData batchData,
|
|
||||||
Map<String, Object> orderDetail) {
|
|
||||||
List<Map<String, String>> videoList = new ArrayList<>();
|
|
||||||
|
|
||||||
List<OrderFile> videoFiles = files.stream()
|
|
||||||
.filter(f -> "raw_video".equals(f.getFileTag()))
|
|
||||||
.toList();
|
|
||||||
|
|
||||||
@SuppressWarnings("unchecked")
|
|
||||||
List<Map<String, String>> imgList = (List<Map<String, String>>) orderDetail.get("imgList");
|
|
||||||
|
|
||||||
for (int i = 0; i < videoFiles.size(); i++) {
|
|
||||||
OrderFile file = videoFiles.get(i);
|
|
||||||
Map<String, String> videoInfo = new HashMap<>();
|
|
||||||
|
|
||||||
videoInfo.put("url", batchData.fileUrlMap.get(file.getFileId()));
|
|
||||||
videoInfo.put("contentType", file.getFileType());
|
|
||||||
videoInfo.put("path", file.getFilePath());
|
|
||||||
|
|
||||||
// 设置视频缩略图
|
|
||||||
String thumbnailUrl = getVideoThumbnail(imgList, i);
|
|
||||||
videoInfo.put("viewUrl", thumbnailUrl);
|
|
||||||
|
|
||||||
videoList.add(videoInfo);
|
|
||||||
}
|
|
||||||
|
|
||||||
return videoList;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 获取视频缩略图URL
|
|
||||||
*/
|
|
||||||
private String getVideoThumbnail(List<Map<String, String>> imgList, int videoIndex) {
|
|
||||||
if (imgList == null || imgList.isEmpty()) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 优先使用对应索引的图片
|
|
||||||
if (videoIndex < imgList.size()) {
|
|
||||||
return imgList.get(videoIndex).get("viewUrl");
|
|
||||||
}
|
|
||||||
|
|
||||||
// 否则使用第一张图片
|
|
||||||
return imgList.get(0).get("viewUrl");
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 判断是否为图片文件
|
|
||||||
*/
|
|
||||||
private boolean isImageFile(String fileType) {
|
|
||||||
return "image/jpeg".equals(fileType)
|
|
||||||
|| "image/jpg".equals(fileType)
|
|
||||||
|| "image/png".equals(fileType);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
+19
-75
@@ -22,9 +22,6 @@ import org.springframework.beans.factory.annotation.Value;
|
|||||||
import org.springframework.util.CollectionUtils;
|
import org.springframework.util.CollectionUtils;
|
||||||
import org.springframework.web.bind.annotation.*;
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
import java.util.concurrent.Executors;
|
|
||||||
import java.util.concurrent.ScheduledExecutorService;
|
|
||||||
import java.util.concurrent.TimeUnit;
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
@@ -43,8 +40,6 @@ import java.util.Map;
|
|||||||
@RequiredArgsConstructor
|
@RequiredArgsConstructor
|
||||||
public class OrderFileController {
|
public class OrderFileController {
|
||||||
|
|
||||||
private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
|
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private IOrderFileService orderFileService;
|
private IOrderFileService orderFileService;
|
||||||
|
|
||||||
@@ -105,8 +100,8 @@ public class OrderFileController {
|
|||||||
fileMap.put("style", fileStyle);
|
fileMap.put("style", fileStyle);
|
||||||
if (pageResult.getResp_code() == 0){
|
if (pageResult.getResp_code() == 0){
|
||||||
for (OrderFile orderFile: pageResult.getData()){
|
for (OrderFile orderFile: pageResult.getData()){
|
||||||
orderFile.setViewUrl(fileCenterService.getFileViewUrl(orderFile.getFileId()));
|
orderFile.setViewUrl(fileCenterService.getViewUrlByPath(orderFile.getFilePath()));
|
||||||
fileMap.put("fileId", orderFile.getFileId());
|
fileMap.put("path", orderFile.getFilePath());
|
||||||
orderFile.setZipViewUrl(fileCenterService.getViewUrlByPathStyle(fileMap));
|
orderFile.setZipViewUrl(fileCenterService.getViewUrlByPathStyle(fileMap));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -261,7 +256,6 @@ public class OrderFileController {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* 检查素材数量是否达到二维码要求,如果达到则更新订单状态为UPLOADED
|
* 检查素材数量是否达到二维码要求,如果达到则更新订单状态为UPLOADED
|
||||||
* 并在7分钟后若仍为UPLOADED则自动更新为COMPLETE
|
|
||||||
* @param order 订单信息
|
* @param order 订单信息
|
||||||
*/
|
*/
|
||||||
private void checkAndUpdateOrderStatus(Order order) {
|
private void checkAndUpdateOrderStatus(Order order) {
|
||||||
@@ -280,43 +274,28 @@ public class OrderFileController {
|
|||||||
log.info("检查素材数量,订单号: {}, 二维码要求数量: {}, 当前上传数量: {}",
|
log.info("检查素材数量,订单号: {}, 二维码要求数量: {}, 当前上传数量: {}",
|
||||||
order.getOrderNo(), qrCode.getMaterialCount(), currentFileCount);
|
order.getOrderNo(), qrCode.getMaterialCount(), currentFileCount);
|
||||||
|
|
||||||
// 如果当前文件数量达到或超过二维码要求的数量,则更新订单状态为素材上传完成(UPLOADED)
|
// 如果当前文件数量达到或超过二维码要求的数量,则更新订单状态为素材上传完成
|
||||||
if (currentFileCount >= qrCode.getMaterialCount()) {
|
if (currentFileCount >= qrCode.getMaterialCount()) {
|
||||||
|
|
||||||
// 并发场景下,实时查询最新订单状态再做判断
|
|
||||||
Order latestOrder = orderService.getOrderByNumber(order.getOrderNo());
|
|
||||||
if (latestOrder == null) {
|
|
||||||
log.warn("达到素材数量阈值时订单不存在: orderNo={}", order.getOrderNo());
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
Tourism tourism = tourismService.getTourismById(qrCode.getTourismId());
|
Tourism tourism = tourismService.getTourismById(qrCode.getTourismId());
|
||||||
|
|
||||||
boolean isComplete = OrderStatus.COMPLETE.getId().equals(latestOrder.getOrderStatus());
|
// 自动更新订单状态为设备执行完成
|
||||||
|
if (!OrderStatus.COMPLETE.getId().equals(order.getOrderStatus())) {
|
||||||
// 更新订单状态为UPLOADED(素材上传完成),但若已为COMPLETE则不更新
|
order.setOrderStatus(OrderStatus.COMPLETE.getId());
|
||||||
if (!isComplete && !OrderStatus.UPLOADED.getId().equals(latestOrder.getOrderStatus())) {
|
boolean updateResult = orderService.updateOrder(order);
|
||||||
Integer oldStatus = latestOrder.getOrderStatus();
|
|
||||||
latestOrder.setOrderStatus(OrderStatus.UPLOADED.getId());
|
|
||||||
boolean updateResult = orderService.updateOrder(latestOrder);
|
|
||||||
if (updateResult) {
|
if (updateResult) {
|
||||||
log.info("订单状态已更新为UPLOADED: orderNo={}, oldStatus={}, newStatus={}",
|
log.info("订单状态已自动更新为设备执行完成: orderNo={}, oldStatus={}, newStatus={}",
|
||||||
latestOrder.getOrderNo(), oldStatus, OrderStatus.UPLOADED.getId());
|
order.getOrderNo(), order.getOrderStatus(), OrderStatus.COMPLETE.getId());
|
||||||
} else {
|
} else {
|
||||||
log.error("订单状态更新为UPLOADED失败: orderNo={}", latestOrder.getOrderNo());
|
log.error("订单状态更新失败: orderNo={}", order.getOrderNo());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
//发送用户素材上传成功通知
|
//发送用户素材上传成功通知
|
||||||
sendMessageForResouresUploaded(latestOrder,tourism);
|
sendMessageForResouresUploaded(order,tourism);
|
||||||
|
|
||||||
// 预热订单相关的文件到CDN
|
// 预热订单相关的文件到CDN
|
||||||
prefetchOrderFilesToCdn(latestOrder.getOrderNo());
|
prefetchOrderFilesToCdn(order.getOrderNo());
|
||||||
|
|
||||||
// 7分钟后如果状态仍为UPLOADED,则自动更新为COMPLETE;若已完成则不再安排
|
|
||||||
if (!isComplete) {
|
|
||||||
scheduleAutoCompleteIfStillUploaded(latestOrder.getOrderNo());
|
|
||||||
}
|
|
||||||
|
|
||||||
// 检查是否开启一键成片功能
|
// 检查是否开启一键成片功能
|
||||||
if (isVideoEditEnabled(qrCode)) {
|
if (isVideoEditEnabled(qrCode)) {
|
||||||
@@ -324,30 +303,30 @@ public class OrderFileController {
|
|||||||
order.getOrderNo(), order.getCodeId());
|
order.getOrderNo(), order.getCodeId());
|
||||||
|
|
||||||
// 检查是否存在进行中的编辑任务
|
// 检查是否存在进行中的编辑任务
|
||||||
EditTask existingTask = editTaskService.getTaskByOrderSn(latestOrder.getOrderNo());
|
EditTask existingTask = editTaskService.getTaskByOrderSn(order.getOrderNo());
|
||||||
if (existingTask != null && EditTaskStatus.isProcessing(existingTask.getStatus())) {
|
if (existingTask != null && EditTaskStatus.isProcessing(existingTask.getStatus())) {
|
||||||
log.info("已存在进行中的编辑任务: orderNo={}, taskId={}", latestOrder.getOrderNo(), existingTask.getId());
|
log.info("已存在进行中的编辑任务: orderNo={}, taskId={}", order.getOrderNo(), existingTask.getId());
|
||||||
return ;
|
return ;
|
||||||
}
|
}
|
||||||
|
|
||||||
//触发一键成片
|
//触发一键成片
|
||||||
// 1. 创建新任务
|
// 1. 创建新任务
|
||||||
EditTask task = editTaskService.createTask(latestOrder.getOrderNo(), latestOrder.getUserId());
|
EditTask task = editTaskService.createTask(order.getOrderNo(), order.getUserId());
|
||||||
|
|
||||||
// 2. 获取素材文件
|
// 2. 获取素材文件
|
||||||
List<OrderFile> orderFiles = orderFileService.getOrderFileByOrderNo(latestOrder.getOrderNo());
|
List<OrderFile> orderFiles = orderFileService.getOrderFileByOrderNo(order.getOrderNo());
|
||||||
|
|
||||||
// 3. 提交编辑任务
|
// 3. 提交编辑任务
|
||||||
String jobId = videoEditService.submitEditTask(latestOrder.getOrderNo(), orderFiles);
|
String jobId = videoEditService.submitEditTask(order.getOrderNo(), orderFiles);
|
||||||
log.info("提交一键成片任务成功: orderNo={}, jobId={}, totalMediaFiles={}",
|
log.info("提交一键成片任务成功: orderNo={}, jobId={}, totalMediaFiles={}",
|
||||||
latestOrder.getOrderNo(), jobId, orderFiles.size());
|
order.getOrderNo(), jobId, orderFiles.size());
|
||||||
// 4. 更新任务信息
|
// 4. 更新任务信息
|
||||||
task.setJobId(jobId);
|
task.setJobId(jobId);
|
||||||
task.setStatus(EditTaskStatus.PROCESSING);
|
task.setStatus(EditTaskStatus.PROCESSING);
|
||||||
editTaskService.saveOrUpdateTask(task);
|
editTaskService.saveOrUpdateTask(task);
|
||||||
} else {
|
} else {
|
||||||
log.info("二维码未开启一键成片功能,跳过一键成片: orderNo={}, codeId={}, enableVideoEdit={}",
|
log.info("二维码未开启一键成片功能,跳过一键成片: orderNo={}, codeId={}, enableVideoEdit={}",
|
||||||
latestOrder.getOrderNo(), latestOrder.getCodeId(), qrCode.getEnableVideoEdit());
|
order.getOrderNo(), order.getCodeId(), qrCode.getEnableVideoEdit());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
@@ -355,41 +334,6 @@ public class OrderFileController {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* 7分钟后检查订单状态是否仍为UPLOADED,如是则自动置为COMPLETE
|
|
||||||
*/
|
|
||||||
private void scheduleAutoCompleteIfStillUploaded(String orderNo) {
|
|
||||||
try {
|
|
||||||
scheduler.schedule(() -> {
|
|
||||||
try {
|
|
||||||
Order latest = orderService.getOrderByNumber(orderNo);
|
|
||||||
if (latest == null) {
|
|
||||||
log.warn("延迟完成检查时订单不存在: orderNo={}", orderNo);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (OrderStatus.UPLOADED.getId().equals(latest.getOrderStatus())) {
|
|
||||||
Integer oldStatus = latest.getOrderStatus();
|
|
||||||
latest.setOrderStatus(OrderStatus.COMPLETE.getId());
|
|
||||||
boolean updated = orderService.updateOrder(latest);
|
|
||||||
if (updated) {
|
|
||||||
log.info("订单状态在7分钟后自动由UPLOADED更新为COMPLETE: orderNo={}, oldStatus={}, newStatus={}",
|
|
||||||
orderNo, oldStatus, OrderStatus.COMPLETE.getId());
|
|
||||||
} else {
|
|
||||||
log.error("订单状态在7分钟后自动更新为COMPLETE失败: orderNo={}", orderNo);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
log.info("订单状态在7分钟后已非UPLOADED,跳过自动完成: orderNo={}, currentStatus={}",
|
|
||||||
orderNo, latest.getOrderStatus());
|
|
||||||
}
|
|
||||||
} catch (Exception e) {
|
|
||||||
log.error("订单状态7分钟后自动完成检查异常: orderNo={}", orderNo, e);
|
|
||||||
}
|
|
||||||
}, 7, TimeUnit.MINUTES);
|
|
||||||
} catch (Exception e) {
|
|
||||||
log.error("安排订单状态自动完成任务失败: orderNo={}", orderNo, e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 检查是否开启一键成片功能
|
* 检查是否开启一键成片功能
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -8,8 +8,7 @@ import lombok.Getter;
|
|||||||
* @author lsl create by 2025/1/10
|
* @author lsl create by 2025/1/10
|
||||||
*/
|
*/
|
||||||
@Getter
|
@Getter
|
||||||
public enum
|
public enum OrderStatus implements ZltEnum {
|
||||||
OrderStatus implements ZltEnum {
|
|
||||||
UNPAID(0,"待支付"),
|
UNPAID(0,"待支付"),
|
||||||
PAID(1, "已支付排队中"),
|
PAID(1, "已支付排队中"),
|
||||||
CANCELED(2, "已取消"),
|
CANCELED(2, "已取消"),
|
||||||
|
|||||||
@@ -38,7 +38,7 @@ public class Order extends SuperEntity {
|
|||||||
@Schema(description = "订单状态")
|
@Schema(description = "订单状态")
|
||||||
private Integer orderStatus;
|
private Integer orderStatus;
|
||||||
|
|
||||||
@Schema(description = "支付类型(1:微信支付,2:优惠券支付, 3: 第三方聚到核销)")
|
@Schema(description = "支付类型(1:微信支付,2:优惠券支付)")
|
||||||
private Integer payType;
|
private Integer payType;
|
||||||
|
|
||||||
private Date payTime;
|
private Date payTime;
|
||||||
|
|||||||
-5
@@ -102,12 +102,7 @@ public class OrderServiceImpl extends SuperServiceImpl<OrderMapper, Order> imple
|
|||||||
// 创建订单,初始状态为"待支付"
|
// 创建订单,初始状态为"待支付"
|
||||||
@Override
|
@Override
|
||||||
public boolean createOrder(Order order) {
|
public boolean createOrder(Order order) {
|
||||||
// payType=3 视为已支付,否则为待支付
|
|
||||||
if (order.getPayType() != null && order.getPayType() == 3) {
|
|
||||||
order.setOrderStatus(OrderStatus.PAID.getId());
|
|
||||||
} else {
|
|
||||||
order.setOrderStatus(OrderStatus.UNPAID.getId());
|
order.setOrderStatus(OrderStatus.UNPAID.getId());
|
||||||
}
|
|
||||||
String orderNo = generateOrderNumber(order.getTourismId());
|
String orderNo = generateOrderNumber(order.getTourismId());
|
||||||
order.setOrderNo(orderNo);
|
order.setOrderNo(orderNo);
|
||||||
|
|
||||||
|
|||||||
-12
@@ -125,16 +125,6 @@ public class S3Template implements InitializingBean {
|
|||||||
return url.toString();
|
return url.toString();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* 获取预览地址
|
|
||||||
* @param path
|
|
||||||
* @return
|
|
||||||
*/
|
|
||||||
public String getViewUrlNoExpires(String path) {
|
|
||||||
String url = fileProperties.getS3().getEndpoint() + PATH_SPLIT+fileProperties.getS3().getBucketName()+ PATH_SPLIT+ path;
|
|
||||||
return url;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void out(String objectName, OutputStream os) {
|
public void out(String objectName, OutputStream os) {
|
||||||
out(fileProperties.getS3().getBucketName(), objectName, os);
|
out(fileProperties.getS3().getBucketName(), objectName, os);
|
||||||
}
|
}
|
||||||
@@ -226,6 +216,4 @@ public class S3Template implements InitializingBean {
|
|||||||
public AmazonS3 getAmazonS3() {
|
public AmazonS3 getAmazonS3() {
|
||||||
return this.amazonS3;
|
return this.amazonS3;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -28,10 +28,8 @@ zlt.fdfs.trackerList=${zlt.fdfs.web-url}:22122
|
|||||||
##### s3配置
|
##### s3配置
|
||||||
zlt.s3.access-key=Hq78CaYg2BI6ZfxCRMKI
|
zlt.s3.access-key=Hq78CaYg2BI6ZfxCRMKI
|
||||||
zlt.s3.accessKeySecret=DJCt5q9K7GQ2zcBEfr3twb1vQ6BgUW1LKFlI5NSw
|
zlt.s3.accessKeySecret=DJCt5q9K7GQ2zcBEfr3twb1vQ6BgUW1LKFlI5NSw
|
||||||
#zlt.s3.endpoint=http://local.goflytec.com:9194
|
|
||||||
#zlt.s3.endpoint=https://local.goflytec.com
|
|
||||||
zlt.s3.endpoint=http://220.205.16.27:9000
|
zlt.s3.endpoint=http://220.205.16.27:9000
|
||||||
zlt.s3.bucketName=goflymedia
|
zlt.s3.bucketName=goflyapp
|
||||||
zlt.s3.region=us-east-1
|
zlt.s3.region=us-east-1
|
||||||
|
|
||||||
zlt.oss.secretId=LTAI5tSNV1RvexXpMMCZhxSe
|
zlt.oss.secretId=LTAI5tSNV1RvexXpMMCZhxSe
|
||||||
|
|||||||
Reference in New Issue
Block a user