11 changed files with 304 additions and 199 deletions
@@ -5,7 +5,6 @@ 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.JsonObject;
import com.central.common.model.Result;
import com.central.common.lock.Lock;
import com.central.device.feign.OrderCenterService;
import com.central.device.message.ControlEnum;
import com.central.device.message.ControlMessageConstant;
@@ -21,6 +20,7 @@ import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
@@ -49,6 +49,9 @@ public class ApiDeviceController {
@Autowired
private RequestUtils requestUtils;
@Autowired
private StringRedisTemplate redisTemplate;
private ControlMessageConstant controlMessageConstant = new ControlMessageConstant();
@Autowired
@@ -78,8 +81,6 @@ public class ApiDeviceController {
*/
@Operation(summary = "设备属性设置")
@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) {
log.info("开始设置设备属性: deviceId={}, param={}", deviceId, param);
try {
@@ -90,23 +91,36 @@ public class ApiDeviceController {
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);
if (!isValidOrderStatus(orderStatus)) {
return Result.failed("设备已处理,请关注订单详情");
}
// 3. 构建控制消息
// 5. 构建控制消息
JsonObject controlMessage = buildControlMessage(control, orderNo, deviceId);
if (controlMessage == null) {
return Result.failed("暂未开放控制权限");
}
// 4. 发送设备控制请求
// 6. 发送设备控制请求
String url = baseUrl + "/device/instance/" + deviceId + "/property";
Map<String, String> result = requestUtils.getPostRequestResultMap(url, controlMessage.toString());
// 5. 处理响应结果
// 7. 处理响应结果
return handleDeviceResponse(result, orderNo);
} catch (Exception e) {
@@ -309,4 +323,47 @@ public class ApiDeviceController {
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);
}
}
}
@@ -120,7 +120,9 @@ public class FileController {
PageResult<FileInfo> pageResult = fileService.findList(params);
if(pageResult.getCount() >0){
for (FileInfo fileInfo: pageResult.getData()){
fileInfo.setUrl(timeWindowStorageService.getSmartViewUrlByPath(fileInfo.getName()));
String url = timeWindowStorageService.getSmartViewUrlByPath(fileInfo.getName());
log.info("文件查询URL: name={}, url={}", fileInfo.getName(), url);
fileInfo.setUrl(url);
}
}
return pageResult;
@@ -136,17 +138,23 @@ public class FileController {
@GetMapping("/files/{id}")
public Result getViewUrl(@PathVariable String id) {
return Result.succeed(timeWindowStorageService.getSmartViewUrl(id),"获取成功");
String url = timeWindowStorageService.getSmartViewUrl(id);
log.info("文件查询URL: id={}, url={}", id, url);
return Result.succeed(url,"获取成功");
}
@GetMapping("/file/path")
public Result getFileViewUrlByPath(@RequestParam String path) {
return Result.succeed(timeWindowStorageService.getSmartViewUrlByPath(path),"获取成功");
String url = timeWindowStorageService.getSmartViewUrlByPath(path);
log.info("文件查询URL: path={}, url={}", path, url);
return Result.succeed(url,"获取成功");
}
@GetMapping("/files/path")
public String getViewUrlByPath(@RequestParam String path) {
return timeWindowStorageService.getSmartViewUrlByPath(path);
String url = timeWindowStorageService.getSmartViewUrlByPath(path);
log.info("文件查询URL: path={}, url={}", path, url);
return url;
}
@GetMapping("/files/path/style")
@@ -4,14 +4,15 @@ import com.central.common.model.FileInfo;
import com.central.file.service.impl.OssService;
import com.central.file.service.impl.S3Service;
import com.central.file.service.impl.EnhancedS3Service;
import com.central.file.mapper.FileMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
/**
* 时间窗口智能存储服务
@@ -36,15 +37,17 @@ public class TimeWindowStorageService {
@Qualifier("enhancedS3FileService")
private EnhancedS3Service enhancedS3Service;
@Autowired(required = false)
private OssToS3SyncService ossToS3SyncService;
// 自动同步逻辑已取消,不再注入同步服务
@Autowired
private FileMapper fileMapper;
// 配置参数
@Value("${zlt.storage.hot-data-days:30}")
private int hotDataDays; // 热数据保留天数,默认30天
// @Value("${zlt.storage.hot-data-days}")
private int hotDataDays = 90; // 热数据保留天数,默认30天
@Value("${zlt.storage.enable-time-window:true}")
private boolean enableTimeWindow; // 是否启用时间窗口存储
// @Value("${zlt.storage.enable-time-window:true}")
private boolean enableTimeWindow = false; // 是否启用时间窗口存储
/**
* 智能获取文件访问URL
@@ -64,6 +67,8 @@ public class TimeWindowStorageService {
// 2. 判断存储类型
String storageType = getStorageTypeByTime(fileInfo);
log.info("时间窗口判定: fileId={} createTime={} hotDataDays={} enableTimeWindow={} -> storageType={}",
fileInfo.getId(), fileInfo.getCreateTime(), hotDataDays, enableTimeWindow, storageType);
// 3. 根据存储类型获取URL
String viewUrl = getViewUrlByStorageType(fileInfo, storageType);
@@ -86,25 +91,82 @@ public class TimeWindowStorageService {
*/
public String getSmartViewUrlByPath(String filePath) {
try {
// 1. 根据路径特征判断存储类型
if (isS3Path(filePath)) {
log.debug("S3路径,直接查询S3: path={}", filePath);
return queryFromS3ByPath(filePath);
} else if (isOssPath(filePath)) {
log.debug("OSS路径,直接查询OSS: path={}", filePath);
return ossService.getViewUrlByPath(filePath);
// 先按路径查询数据库,若查到则走时间窗口策略
FileInfo fileInfo = getFileInfoByPath(filePath);
if (fileInfo != null) {
String storageType = getStorageTypeByTime(fileInfo);
log.info("[PATH] 时间窗口判定: path={} createTime={} hotDataDays={} enableTimeWindow={} -> storageType={}",
filePath, fileInfo.getCreateTime(), hotDataDays, enableTimeWindow, storageType);
String url = getViewUrlByStorageType(fileInfo, storageType);
log.info("[PATH] 按时间窗口获取URL: path={} storageType={} url={}", filePath, storageType, url);
return url;
}
// 若DB无记录,仍按时间窗口开关执行策略:
// - 若未启用时间窗口:按热数据策略(OSS)
// - 若启用时间窗口:作为未知创建时间,采用冷优先(S3→OSS)的策略
if (!enableTimeWindow) {
log.warn("[PATH] 数据库未找到文件信息,时间窗口关闭,直接从OSS获取: path={}", 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);
// 1) 先尝试S3(不触发任何自动同步)
String s3Url = queryFromS3ByPath(filePath);
if (s3Url != null && !s3Url.isEmpty()) {
log.debug("S3查询成功: path={}", filePath);
return s3Url;
}
// 2) 再尝试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());
}
log.warn("路径查询失败(OSS/S3均未命中): path={}", filePath);
return "";
}
// 2. 路径特征不明确,尝试智能查询
log.debug("路径特征不明确,尝试智能查询: path={}", filePath);
return getViewUrlByFallback(filePath);
} catch (Exception e) {
log.error("智能存储查询失败: path={}, error={}", filePath, e.getMessage(), e);
log.error("智能存储路径查询异常: path={}, error={}", filePath, e.getMessage(), e);
return "";
}
}
private FileInfo getFileInfoByPath(String filePath) {
try {
if (filePath == null || filePath.isEmpty()) {
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;
}
}
/**
* 根据文件创建时间判断存储类型
*/
@@ -155,7 +217,9 @@ public class TimeWindowStorageService {
}
// S3查询失败,降级到OSS
log.warn("S3查询失败,降级到OSS: fileId={}", fileInfo.getId());
return queryFromOss(fileInfo);
String ossUrl = queryFromOss(fileInfo);
log.info("OSS降级查询结果: fileId={}, url={}", fileInfo.getId(), ossUrl);
return ossUrl;
} else {
// 热数据,优先从OSS查询
log.info("热数据,优先从OSS查询: fileId={}", fileInfo.getId());
@@ -166,7 +230,9 @@ public class TimeWindowStorageService {
}
// OSS查询失败,降级到S3
log.warn("OSS查询失败,降级到S3: fileId={}", fileInfo.getId());
return queryFromS3(fileInfo);
String s3Url = queryFromS3(fileInfo);
log.info("S3降级查询结果: fileId={}, url={}", fileInfo.getId(), s3Url);
return s3Url;
}
}
@@ -175,7 +241,13 @@ public class TimeWindowStorageService {
*/
private String queryFromOss(FileInfo fileInfo) {
try {
return ossService.getViewUrlByPath(fileInfo.getPath());
String url = ossService.getViewUrlByPath(fileInfo.getPath());
if (url == null || url.isEmpty()) {
log.warn("从OSS查询为空: fileId={} path={}", fileInfo.getId(), fileInfo.getPath());
} else {
log.debug("从OSS获取URL: fileId={} url={}", fileInfo.getId(), url);
}
return url;
} catch (Exception e) {
log.warn("从OSS查询失败: fileId={}, error={}", fileInfo.getId(), e.getMessage());
return "";
@@ -190,10 +262,22 @@ public class TimeWindowStorageService {
// 优先使用EnhancedS3Service
if (enhancedS3Service != null) {
log.debug("使用EnhancedS3Service查询: fileId={}, path={}", fileInfo.getId(), fileInfo.getPath());
return enhancedS3Service.getViewUrlByPath(fileInfo.getPath());
String url = enhancedS3Service.getViewUrlByPath(fileInfo.getPath());
if (url == null || url.isEmpty()) {
log.warn("从S3查询为空(Enhanced): fileId={} path={}", fileInfo.getId(), fileInfo.getPath());
} else {
log.debug("从S3获取URL(Enhanced): fileId={} url={}", fileInfo.getId(), url);
}
return url;
} else if (s3Service != null) {
log.debug("使用S3Service查询: fileId={}, path={}", fileInfo.getId(), fileInfo.getPath());
return s3Service.getViewUrlByPath(fileInfo.getPath());
String url = s3Service.getViewUrlByPath(fileInfo.getPath());
if (url == null || url.isEmpty()) {
log.warn("从S3查询为空(基础): fileId={} path={}", fileInfo.getId(), fileInfo.getPath());
} else {
log.debug("从S3获取URL(基础): fileId={} url={}", fileInfo.getId(), url);
}
return url;
} else {
log.warn("S3服务未配置,无法查询S3: fileId={}", fileInfo.getId());
return "";
@@ -212,21 +296,7 @@ public class TimeWindowStorageService {
// 优先使用EnhancedS3Service
if (enhancedS3Service != null) {
log.debug("使用EnhancedS3Service查询: path={}", filePath);
String s3Url = enhancedS3Service.getViewUrlByPath(filePath);
// 如果S3中没有找到文件,尝试从OSS同步
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 {
log.warn("OSS同步到S3失败: path={}", filePath);
}
}
return s3Url;
return enhancedS3Service.getViewUrlByPath(filePath);
} else if (s3Service != null) {
log.debug("使用S3Service查询: path={}", filePath);
return s3Service.getViewUrlByPath(filePath);
@@ -243,61 +313,19 @@ 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 "";
}
// 删除未使用的降级方法以消除告警
// private String getViewUrlByFallback(String 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://")
);
}
// 删除未使用的方法以消除告警
// private boolean isS3Path(String path) { return false; }
/**
* 判断是否为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/")
);
}
// private boolean isOssPath(String path) { return false; }
/**
* 检查文件是否需要迁移
@@ -1,7 +1,6 @@
package com.central.file.service.impl;
import cn.hutool.core.util.StrUtil;
import com.central.common.constant.CommonConstant;
import com.central.common.model.FileInfo;
import com.central.oss.model.ObjectInfo;
import com.central.oss.properties.FileServerProperties;
@@ -69,17 +68,18 @@ public class EnhancedS3Service extends AbstractIFileService {
try {
S3Object s3Object = parsePath(name);
log.info("解析S3路径: {} -> bucket: {}, object: {}", name, s3Object.bucketName, s3Object.objectName);
// 检查文件是否存在
boolean exists = s3Template.doesObjectExist(s3Object.bucketName, s3Object.objectName);
log.info("S3文件存在检查: bucket={}, object={}, exists={}", s3Object.bucketName, s3Object.objectName, exists);
if (!exists) {
log.warn("S3文件不存在: bucket={}, object={}", s3Object.bucketName, s3Object.objectName);
return "";
// 打印未签名的S3完整访问路径(endpoint/bucket/object)
try {
String endpoint = fileServerProperties.getS3().getEndpoint();
if (endpoint != null && !endpoint.isEmpty()) {
String normalizedEndpoint = endpoint.endsWith("/") ? endpoint.substring(0, endpoint.length() - 1) : endpoint;
String rawUrl = normalizedEndpoint + "/" + s3Object.bucketName + "/" + s3Object.objectName;
log.info("S3访问完整路径(未签名): {}", rawUrl);
}
} catch (Exception ignore) {
}
// 使用getViewUrl方法获取预签名URL
// 直接生成预签名URL,避免额外的HEAD存在性检查引发的握手问题
String url = s3Template.getViewUrl(s3Object.bucketName, s3Object.objectName, 60); // 60分钟有效期
log.info("生成S3 URL: {}", url);
return url;
@@ -336,7 +336,7 @@ public class EnhancedS3Service extends AbstractIFileService {
private S3Object parsePath(String path) {
S3Object s3Object = new S3Object();
if (StrUtil.isNotEmpty(path)) {
// 处理s3://bucket/object格式
// 1) 显式 s3://bucket/object 格式
if (path.startsWith("s3://")) {
String[] parts = path.substring(5).split("/", 2);
if (parts.length >= 2) {
@@ -346,23 +346,25 @@ public class EnhancedS3Service extends AbstractIFileService {
s3Object.bucketName = fileServerProperties.getS3().getBucketName();
s3Object.objectName = decodeUrl(parts[0]);
}
} else if (path.startsWith("hot-sync/")) {
// 处理hot-sync前缀的路径(兼容旧格式)
s3Object.bucketName = fileServerProperties.getS3().getBucketName();
s3Object.objectName = decodeUrl(path.substring("hot-sync/".length())); // 去掉hot-sync/前缀并解码
} else {
// 处理相对路径或无前缀路径
int splitIndex = path.lastIndexOf(CommonConstant.PATH_SPLIT);
if (splitIndex != -1) {
s3Object.bucketName = path.substring(0, splitIndex);
s3Object.objectName = decodeUrl(path.substring(splitIndex + 1));
} else {
// 如果没有分隔符,使用配置的bucket
s3Object.bucketName = fileServerProperties.getS3().getBucketName();
s3Object.objectName = decodeUrl(path);
}
return s3Object;
}
// 2) 兼容历史 hot-sync/ 前缀:对象名去掉前缀,bucket 用配置
if (path.startsWith("hot-sync/")) {
s3Object.bucketName = fileServerProperties.getS3().getBucketName();
s3Object.objectName = decodeUrl(path.substring("hot-sync/".length()));
return s3Object;
}
// 3) 统一相对路径策略:bucket 固定取配置,objectName 使用完整 path
// 这样与 OSS 目录保持一致:同一个 filePath 在 S3 作为对象键
s3Object.bucketName = fileServerProperties.getS3().getBucketName();
s3Object.objectName = decodeUrl(path);
return s3Object;
}
// path 为空时,退回配置 bucket,空对象名
s3Object.bucketName = fileServerProperties.getS3().getBucketName();
s3Object.objectName = "";
return s3Object;
}
@@ -1,36 +0,0 @@
# 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
@@ -47,25 +47,7 @@ zlt:
bucketName: ${zlt.oss.bucketName}
# 时间窗口存储配置
storage:
enable-time-window: true # 启用时间窗口智能存储
hot-data-days: 30 # 热数据保留天数
migration:
enable-verification: true # 启用迁移验证
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:
enable: false
@@ -22,6 +22,9 @@ import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
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.HashMap;
import java.util.List;
@@ -40,6 +43,8 @@ import java.util.Map;
@RequiredArgsConstructor
public class OrderFileController {
private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
@Autowired
private IOrderFileService orderFileService;
@@ -256,6 +261,7 @@ public class OrderFileController {
/**
* 检查素材数量是否达到二维码要求,如果达到则更新订单状态为UPLOADED
* 并在7分钟后若仍为UPLOADED则自动更新为COMPLETE
* @param order 订单信息
*/
private void checkAndUpdateOrderStatus(Order order) {
@@ -274,28 +280,43 @@ public class OrderFileController {
log.info("检查素材数量,订单号: {}, 二维码要求数量: {}, 当前上传数量: {}",
order.getOrderNo(), qrCode.getMaterialCount(), currentFileCount);
// 如果当前文件数量达到或超过二维码要求的数量,则更新订单状态为素材上传完成
// 如果当前文件数量达到或超过二维码要求的数量,则更新订单状态为素材上传完成(UPLOADED)
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());
// 自动更新订单状态为设备执行完成
if (!OrderStatus.COMPLETE.getId().equals(order.getOrderStatus())) {
order.setOrderStatus(OrderStatus.COMPLETE.getId());
boolean updateResult = orderService.updateOrder(order);
boolean isComplete = OrderStatus.COMPLETE.getId().equals(latestOrder.getOrderStatus());
// 更新订单状态为UPLOADED(素材上传完成),但若已为COMPLETE则不更新
if (!isComplete && !OrderStatus.UPLOADED.getId().equals(latestOrder.getOrderStatus())) {
Integer oldStatus = latestOrder.getOrderStatus();
latestOrder.setOrderStatus(OrderStatus.UPLOADED.getId());
boolean updateResult = orderService.updateOrder(latestOrder);
if (updateResult) {
log.info("订单状态已自动更新为设备执行完成: orderNo={}, oldStatus={}, newStatus={}",
order.getOrderNo(), order.getOrderStatus(), OrderStatus.COMPLETE.getId());
log.info("订单状态已更新为UPLOADED: orderNo={}, oldStatus={}, newStatus={}",
latestOrder.getOrderNo(), oldStatus, OrderStatus.UPLOADED.getId());
} else {
log.error("订单状态更新失败: orderNo={}", order.getOrderNo());
log.error("订单状态更新为UPLOADED失败: orderNo={}", latestOrder.getOrderNo());
}
}
//发送用户素材上传成功通知
sendMessageForResouresUploaded(order,tourism);
sendMessageForResouresUploaded(latestOrder,tourism);
// 预热订单相关的文件到CDN
prefetchOrderFilesToCdn(order.getOrderNo());
prefetchOrderFilesToCdn(latestOrder.getOrderNo());
// 7分钟后如果状态仍为UPLOADED,则自动更新为COMPLETE;若已完成则不再安排
if (!isComplete) {
scheduleAutoCompleteIfStillUploaded(latestOrder.getOrderNo());
}
// 检查是否开启一键成片功能
if (isVideoEditEnabled(qrCode)) {
@@ -303,30 +324,30 @@ public class OrderFileController {
order.getOrderNo(), order.getCodeId());
// 检查是否存在进行中的编辑任务
EditTask existingTask = editTaskService.getTaskByOrderSn(order.getOrderNo());
EditTask existingTask = editTaskService.getTaskByOrderSn(latestOrder.getOrderNo());
if (existingTask != null && EditTaskStatus.isProcessing(existingTask.getStatus())) {
log.info("已存在进行中的编辑任务: orderNo={}, taskId={}", order.getOrderNo(), existingTask.getId());
log.info("已存在进行中的编辑任务: orderNo={}, taskId={}", latestOrder.getOrderNo(), existingTask.getId());
return ;
}
//触发一键成片
// 1. 创建新任务
EditTask task = editTaskService.createTask(order.getOrderNo(), order.getUserId());
EditTask task = editTaskService.createTask(latestOrder.getOrderNo(), latestOrder.getUserId());
// 2. 获取素材文件
List<OrderFile> orderFiles = orderFileService.getOrderFileByOrderNo(order.getOrderNo());
List<OrderFile> orderFiles = orderFileService.getOrderFileByOrderNo(latestOrder.getOrderNo());
// 3. 提交编辑任务
String jobId = videoEditService.submitEditTask(order.getOrderNo(), orderFiles);
String jobId = videoEditService.submitEditTask(latestOrder.getOrderNo(), orderFiles);
log.info("提交一键成片任务成功: orderNo={}, jobId={}, totalMediaFiles={}",
order.getOrderNo(), jobId, orderFiles.size());
latestOrder.getOrderNo(), jobId, orderFiles.size());
// 4. 更新任务信息
task.setJobId(jobId);
task.setStatus(EditTaskStatus.PROCESSING);
editTaskService.saveOrUpdateTask(task);
} else {
log.info("二维码未开启一键成片功能,跳过一键成片: orderNo={}, codeId={}, enableVideoEdit={}",
order.getOrderNo(), order.getCodeId(), qrCode.getEnableVideoEdit());
latestOrder.getOrderNo(), latestOrder.getCodeId(), qrCode.getEnableVideoEdit());
}
}
} catch (Exception e) {
@@ -334,6 +355,41 @@ 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,7 +8,8 @@ import lombok.Getter;
* @author lsl create by 2025/1/10
*/
@Getter
public enum OrderStatus implements ZltEnum {
public enum
OrderStatus implements ZltEnum {
UNPAID(0,"待支付"),
PAID(1, "已支付排队中"),
CANCELED(2, "已取消"),
@@ -38,7 +38,7 @@ public class Order extends SuperEntity {
@Schema(description = "订单状态")
private Integer orderStatus;
@Schema(description = "支付类型(1:微信支付,2:优惠券支付)")
@Schema(description = "支付类型(1:微信支付,2:优惠券支付, 3: 第三方聚到核销)")
private Integer payType;
private Date payTime;
@@ -102,7 +102,12 @@ public class OrderServiceImpl extends SuperServiceImpl<OrderMapper, Order> imple
// 创建订单,初始状态为"待支付"
@Override
public boolean createOrder(Order order) {
order.setOrderStatus(OrderStatus.UNPAID.getId());
// payType=3 视为已支付,否则为待支付
if (order.getPayType() != null && order.getPayType() == 3) {
order.setOrderStatus(OrderStatus.PAID.getId());
} else {
order.setOrderStatus(OrderStatus.UNPAID.getId());
}
String orderNo = generateOrderNumber(order.getTourismId());
order.setOrderNo(orderNo);
@@ -28,8 +28,10 @@ zlt.fdfs.trackerList=${zlt.fdfs.web-url}:22122
##### s3配置
zlt.s3.access-key=Hq78CaYg2BI6ZfxCRMKI
zlt.s3.accessKeySecret=DJCt5q9K7GQ2zcBEfr3twb1vQ6BgUW1LKFlI5NSw
zlt.s3.endpoint=http://220.205.16.27:9000
zlt.s3.bucketName=goflyapp
#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.bucketName=goflymedia
zlt.s3.region=us-east-1
zlt.oss.secretId=LTAI5tSNV1RvexXpMMCZhxSe