统一文件对象存储上传链路

This commit is contained in:
2026-07-12 15:45:16 +08:00
parent 5ca375f14b
commit 6d91fecad4
10 changed files with 339 additions and 99 deletions
@@ -2,16 +2,13 @@ package com.xiaowang.jayucloud.core.modules.content.controller.front;
import com.xiaowang.jayucloud.core.annotation.OperationGuard;
import com.xiaowang.jayucloud.core.common.Result;
import com.xiaowang.jayucloud.core.config.ObjectStorageProperties;
import com.xiaowang.jayucloud.core.modules.content.dto.CommentDTO;
import com.xiaowang.jayucloud.core.modules.content.service.CommentService;
import com.xiaowang.jayucloud.core.modules.content.vo.CommentVO;
import com.xiaowang.jayucloud.core.modules.file.dto.ChunkUploadCompleteRequestDTO;
import com.xiaowang.jayucloud.core.modules.file.dto.ChunkUploadInitRequestDTO;
import com.xiaowang.jayucloud.core.modules.file.dto.ObjectStorageFileDTO;
import com.xiaowang.jayucloud.core.modules.file.service.ChunkUploadService;
import com.xiaowang.jayucloud.core.modules.file.service.ObjectStorageFileService;
import com.xiaowang.jayucloud.core.modules.file.service.PrimaryObjectStorageService;
import com.xiaowang.jayucloud.core.modules.file.vo.ObjectStorageFileVO;
import com.xiaowang.jayucloud.core.support.id.TimeOrderedSnowflakeIdGenerator;
import com.xiaowang.jayucloud.core.support.security.UploadSecurityValidator;
@@ -39,11 +36,9 @@ public class CommentController {
private final CommentService commentService;
private final ObjectStorageFileService objectStorageFileService;
private final PrimaryObjectStorageService primaryObjectStorageService;
private final ChunkUploadService chunkUploadService;
private final TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator;
private final UploadSecurityValidator uploadSecurityValidator;
private final ObjectStorageProperties objectStorageProperties;
@PostMapping("/create")
public Result<Long> createComment(HttpServletRequest request, @RequestBody CommentDTO commentDTO) {
@@ -63,8 +58,14 @@ public class CommentController {
uploadSecurityValidator.validate(file);
String originalFilename = normalizeOriginalFilename(file.getOriginalFilename());
String objectName = snowflakeIdGenerator.nextIdString() + resolveFileExtension(originalFilename);
String fileUrl = primaryObjectStorageService.uploadFile(file, objectName);
return Result.success(createCommentImageRecord(originalFilename, fileUrl, objectName, file.getContentType(), file.getSize()));
ObjectStorageFileVO fileVO = objectStorageFileService.uploadManagedObjectFile(
originalFilename,
file.getInputStream(),
file.getSize(),
file.getContentType(),
objectName
);
return Result.success(fileVO);
} catch (Exception e) {
e.printStackTrace();
return Result.error("评价图片上传失败: " + e.getMessage());
@@ -110,8 +111,13 @@ public class CommentController {
FileInputStream inputStream = new FileInputStream(preparedUploadFile.getFile())) {
String originalFilename = normalizeOriginalFilename(preparedUploadFile.getFileName());
String objectName = snowflakeIdGenerator.nextIdString() + resolveFileExtension(originalFilename);
String fileUrl = primaryObjectStorageService.uploadStream(inputStream, preparedUploadFile.getFileSize(), preparedUploadFile.getContentType(), objectName);
ObjectStorageFileVO fileVO = createCommentImageRecord(originalFilename, fileUrl, objectName, preparedUploadFile.getContentType(), preparedUploadFile.getFileSize());
ObjectStorageFileVO fileVO = objectStorageFileService.uploadManagedObjectFile(
originalFilename,
inputStream,
preparedUploadFile.getFileSize(),
preparedUploadFile.getContentType(),
objectName
);
chunkUploadService.clearCommentImageUpload(userId, requestDTO.getUploadId());
return Result.success(fileVO);
} catch (Exception e) {
@@ -181,24 +187,6 @@ public class CommentController {
return Result.success(commentVOs);
}
private ObjectStorageFileVO createCommentImageRecord(String originalFilename, String fileUrl, String objectName, String contentType, Long fileSize) {
ObjectStorageFileDTO dto = new ObjectStorageFileDTO();
dto.setFileName(originalFilename);
dto.setFileUrl(fileUrl);
dto.setObjectName(objectName);
dto.setPrimaryProvider(objectStorageProperties.getPrimaryProvider());
dto.setPrimaryUrl(fileUrl);
dto.setBackupProvider(objectStorageProperties.getBackupProvider());
dto.setContentType(contentType);
dto.setFileSize(fileSize);
dto.setPrimaryUploadStatus(1);
dto.setBackupUploadStatus(0);
dto.setBackupRetryCount(0);
dto.setStatus(1);
Long fileId = objectStorageFileService.createObjectStorageFile(dto);
return objectStorageFileService.getObjectStorageFileById(fileId);
}
private String normalizeOriginalFilename(String originalFilename) {
if (originalFilename == null || originalFilename.isBlank()) {
return "comment-image";
@@ -1,15 +1,12 @@
package com.xiaowang.jayucloud.core.modules.file.controller.front;
import com.xiaowang.jayucloud.core.annotation.OperationGuard;
import com.xiaowang.jayucloud.core.config.ObjectStorageProperties;
import com.xiaowang.jayucloud.core.common.Result;
import com.xiaowang.jayucloud.core.modules.file.dto.ChunkUploadCompleteRequestDTO;
import com.xiaowang.jayucloud.core.modules.file.dto.ChunkUploadInitRequestDTO;
import com.xiaowang.jayucloud.core.modules.file.dto.ObjectStorageFileDTO;
import com.xiaowang.jayucloud.core.modules.file.dto.ObjectStorageUploadOutcome;
import com.xiaowang.jayucloud.core.modules.file.service.ChunkUploadService;
import com.xiaowang.jayucloud.core.modules.file.service.ObjectStorageFileService;
import com.xiaowang.jayucloud.core.modules.file.service.ObjectStorageOrchestrationService;
import com.xiaowang.jayucloud.core.modules.file.support.ObjectStorageUrlSupport;
import com.xiaowang.jayucloud.core.support.id.TimeOrderedSnowflakeIdGenerator;
import com.xiaowang.jayucloud.core.support.security.OperationGuardStrategy;
@@ -46,10 +43,6 @@ public class ObjectStorageFileController {
* Variable `objectStorageFileService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final ObjectStorageFileService objectStorageFileService;
/**
* Variable `objectStorageOrchestrationService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final ObjectStorageOrchestrationService objectStorageOrchestrationService;
/**
* Variable `chunkUploadService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
@@ -67,7 +60,6 @@ public class ObjectStorageFileController {
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private final UploadSecurityValidator uploadSecurityValidator;
private final ObjectStorageProperties objectStorageProperties;
@PostMapping("/upload/init")
@OperationGuard(action = "admin-upload-init", ttlSeconds = 10, message = "上传处理中,请勿重复操作")
@@ -103,31 +95,15 @@ public class ObjectStorageFileController {
String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
String objectName = snowflakeIdGenerator.nextIdString() + fileExtension;
ObjectStorageUploadOutcome uploadOutcome = objectStorageOrchestrationService.uploadPrimary(
ObjectStorageFileVO fileVO = objectStorageFileService.uploadManagedObjectFile(
originalFilename,
inputStream,
preparedUploadFile.getFileSize(),
preparedUploadFile.getContentType(),
objectName
);
ObjectStorageFileDTO dto = new ObjectStorageFileDTO();
dto.setFileName(originalFilename);
dto.setFileUrl(uploadOutcome.getPrimaryUrl());
dto.setObjectName(objectName);
dto.setPrimaryProvider(uploadOutcome.getPrimaryProvider());
dto.setPrimaryUrl(uploadOutcome.getPrimaryUrl());
dto.setBackupProvider(String.join(",", objectStorageProperties.getReplicaRequiredProviders()));
dto.setContentType(preparedUploadFile.getContentType());
dto.setFileSize(preparedUploadFile.getFileSize());
dto.setPrimaryUploadStatus(1);
dto.setBackupUploadStatus(0);
dto.setBackupRetryCount(0);
dto.setUploadAttempts(uploadOutcome.getAttempts());
dto.setStatus(1);
Long fileId = objectStorageFileService.createObjectStorageFile(dto);
chunkUploadService.clearAdminObjectStorageUpload(userId, requestDTO.getUploadId());
return Result.success(objectStorageFileService.getObjectStorageFileById(fileId));
return Result.success(fileVO);
} catch (Exception e) {
e.printStackTrace();
return Result.error("文件上传失败: " + e.getMessage());
@@ -161,30 +137,14 @@ public class ObjectStorageFileController {
String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
String objectName = snowflakeIdGenerator.nextIdString() + fileExtension;
ObjectStorageUploadOutcome uploadOutcome = objectStorageOrchestrationService.uploadPrimary(
ObjectStorageFileVO fileVO = objectStorageFileService.uploadManagedObjectFile(
originalFilename,
file.getInputStream(),
file.getSize(),
file.getContentType(),
objectName
);
ObjectStorageFileDTO dto = new ObjectStorageFileDTO();
dto.setFileName(originalFilename);
dto.setFileUrl(uploadOutcome.getPrimaryUrl());
dto.setObjectName(objectName);
dto.setPrimaryProvider(uploadOutcome.getPrimaryProvider());
dto.setPrimaryUrl(uploadOutcome.getPrimaryUrl());
dto.setBackupProvider(String.join(",", objectStorageProperties.getReplicaRequiredProviders()));
dto.setContentType(file.getContentType());
dto.setFileSize(file.getSize());
dto.setPrimaryUploadStatus(1);
dto.setBackupUploadStatus(0);
dto.setBackupRetryCount(0);
dto.setUploadAttempts(uploadOutcome.getAttempts());
dto.setStatus(1);
Long fileId = objectStorageFileService.createObjectStorageFile(dto);
return Result.success(objectStorageFileService.getObjectStorageFileById(fileId));
return Result.success(fileVO);
} catch (Exception e) {
e.printStackTrace();
return Result.error("文件上传失败: " + e.getMessage());
@@ -5,6 +5,7 @@ import com.xiaowang.jayucloud.core.modules.file.entity.ObjectStorageFileDO;
import com.xiaowang.jayucloud.core.modules.file.dto.ObjectStorageFileDTO;
import com.xiaowang.jayucloud.core.modules.file.vo.ObjectStorageFileVO;
import java.io.InputStream;
import java.util.Collection;
import java.util.List;
import java.util.Map;
@@ -26,6 +27,12 @@ public interface ObjectStorageFileService extends IService<ObjectStorageFileDO>
*/
Long createObjectStorageFile(ObjectStorageFileDTO objectStorageFileDTO);
ObjectStorageFileVO uploadManagedObjectFile(String fileName,
InputStream inputStream,
long fileSize,
String contentType,
String objectName) throws Exception;
/**
* 更新文件
*
@@ -6,10 +6,12 @@ import com.xiaowang.jayucloud.core.config.AppCacheProperties;
import com.xiaowang.jayucloud.core.config.ObjectStorageProperties;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaowang.jayucloud.core.modules.file.dto.ObjectStorageFileDTO;
import com.xiaowang.jayucloud.core.modules.file.dto.ObjectStorageUploadOutcome;
import com.xiaowang.jayucloud.core.modules.file.entity.ObjectStorageFileDO;
import com.xiaowang.jayucloud.core.modules.file.mapper.ObjectStorageFileMapper;
import com.xiaowang.jayucloud.core.modules.file.mq.ObjectStorageBackupMessagePublisher;
import com.xiaowang.jayucloud.core.modules.file.service.ObjectStorageFileService;
import com.xiaowang.jayucloud.core.modules.file.service.ObjectStorageOrchestrationService;
import com.xiaowang.jayucloud.core.modules.file.service.ObjectStorageReplicaService;
import com.xiaowang.jayucloud.core.support.cache.MultiLevelCacheService;
import com.xiaowang.jayucloud.core.modules.file.vo.ObjectStorageFileVO;
@@ -18,6 +20,7 @@ import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import java.io.InputStream;
import java.time.Duration;
import java.util.Collection;
import java.util.Collections;
@@ -60,6 +63,7 @@ public class ObjectStorageFileServiceImpl extends ServiceImpl<ObjectStorageFileM
private final ObjectStorageBackupMessagePublisher objectStorageBackupMessagePublisher;
private final ObjectStorageProperties objectStorageProperties;
private final ObjectStorageReplicaService objectStorageReplicaService;
private final ObjectStorageOrchestrationService objectStorageOrchestrationService;
@Override
/**
@@ -78,6 +82,29 @@ public class ObjectStorageFileServiceImpl extends ServiceImpl<ObjectStorageFileM
return objectStorageFileDO.getId();
}
@Override
public ObjectStorageFileVO uploadManagedObjectFile(String fileName,
InputStream inputStream,
long fileSize,
String contentType,
String objectName) throws Exception {
if (!StringUtils.hasText(fileName)) {
throw new IllegalArgumentException("文件名称不能为空");
}
if (!StringUtils.hasText(objectName)) {
throw new IllegalArgumentException("对象存储 objectName 不能为空");
}
ObjectStorageUploadOutcome uploadOutcome = objectStorageOrchestrationService.uploadPrimary(
inputStream,
fileSize,
contentType,
objectName
);
ObjectStorageFileDTO dto = buildUploadedFileDTO(fileName, fileSize, contentType, objectName, uploadOutcome);
Long fileId = createObjectStorageFile(dto);
return getObjectStorageFileById(fileId);
}
@Override
/**
* Update an existing record.
@@ -271,6 +298,28 @@ public class ObjectStorageFileServiceImpl extends ServiceImpl<ObjectStorageFileM
objectStorageFileDO.setRecycleTime(objectStorageFileDTO.getRecycleTime());
}
private ObjectStorageFileDTO buildUploadedFileDTO(String fileName,
long fileSize,
String contentType,
String objectName,
ObjectStorageUploadOutcome uploadOutcome) {
ObjectStorageFileDTO dto = new ObjectStorageFileDTO();
dto.setFileName(fileName);
dto.setFileUrl(uploadOutcome.getPrimaryUrl());
dto.setObjectName(objectName);
dto.setPrimaryProvider(uploadOutcome.getPrimaryProvider());
dto.setPrimaryUrl(uploadOutcome.getPrimaryUrl());
dto.setBackupProvider(String.join(",", objectStorageProperties.getReplicaRequiredProviders()));
dto.setContentType(contentType);
dto.setFileSize(fileSize);
dto.setPrimaryUploadStatus(1);
dto.setBackupUploadStatus(0);
dto.setBackupRetryCount(0);
dto.setUploadAttempts(uploadOutcome.getAttempts());
dto.setStatus(1);
return dto;
}
private void publishBackupIfNeeded(ObjectStorageFileDO objectStorageFileDO) {
if (StringUtils.hasText(objectStorageFileDO.getObjectName())
&& objectStorageProperties.getProviderOrder().contains(objectStorageFileDO.getPrimaryProvider())
@@ -1,10 +1,11 @@
package com.xiaowang.jayucloud.core.modules.file.support;
import com.xiaowang.jayucloud.core.config.ObjectStorageProperties;
import com.xiaowang.jayucloud.core.modules.file.config.AliyunOssConfig;
import com.xiaowang.jayucloud.core.modules.file.config.MinioStorageConfig;
import com.xiaowang.jayucloud.core.modules.file.config.QiniuKodoConfig;
import com.xiaowang.jayucloud.core.modules.file.service.AliyunOssService;
import com.xiaowang.jayucloud.core.modules.file.service.ObjectStorageOrchestrationService;
import com.xiaowang.jayucloud.core.modules.file.service.PrimaryObjectStorageService;
import com.xiaowang.jayucloud.core.modules.file.vo.ObjectStorageFileVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@@ -20,8 +21,9 @@ public class ObjectStorageUrlSupport {
private static final int UPLOAD_STATUS_SUCCEEDED = 1;
private final PrimaryObjectStorageService primaryObjectStorageService;
private final QiniuKodoConfig qiniuKodoConfig;
private final MinioStorageConfig minioStorageConfig;
private final AliyunOssConfig aliyunOssConfig;
private final AliyunOssService aliyunOssService;
private final ObjectStorageProperties objectStorageProperties;
private final ObjectStorageOrchestrationService objectStorageOrchestrationService;
@@ -107,7 +109,7 @@ public class ObjectStorageUrlSupport {
if (!StringUtils.hasText(objectName)) {
return fileUrl;
}
return primaryObjectStorageService.getFileUrl(objectName);
return fileUrl.trim();
}
public String extractObjectName(String fileUrl) {
@@ -116,17 +118,24 @@ public class ObjectStorageUrlSupport {
}
String normalizedUrl = fileUrl.trim();
if (normalizedUrl.startsWith("oss://")) {
return extractAliyunOssObjectName(normalizedUrl);
}
if (!normalizedUrl.startsWith("http://") && !normalizedUrl.startsWith("https://")) {
return stripQuery(stripLeadingSlash(normalizedUrl));
}
try {
URI fileUri = URI.create(normalizedUrl);
URI domainUri = URI.create(normalizeDomain(qiniuKodoConfig.getDomain()));
if (!sameAuthority(fileUri, domainUri)) {
return "";
String qiniuObjectName = extractHttpProviderObjectName(fileUri, qiniuKodoConfig.getDomain(), null);
if (StringUtils.hasText(qiniuObjectName)) {
return qiniuObjectName;
}
return stripQuery(stripLeadingSlash(fileUri.getPath()));
String minioObjectName = extractHttpProviderObjectName(fileUri, minioStorageConfig.getEndpoint(), minioStorageConfig.getBucketName());
if (StringUtils.hasText(minioObjectName)) {
return minioObjectName;
}
return extractAliyunHttpObjectName(fileUri);
} catch (Exception e) {
log.warn("解析对象存储链接失败, fileUrl={}", fileUrl, e);
return "";
@@ -163,6 +172,9 @@ public class ObjectStorageUrlSupport {
}
private String normalizeDomain(String domain) {
if (!StringUtils.hasText(domain)) {
return "";
}
String normalized = domain.trim();
while (normalized.endsWith("/")) {
normalized = normalized.substring(0, normalized.length() - 1);
@@ -173,6 +185,72 @@ public class ObjectStorageUrlSupport {
return normalized;
}
private String extractHttpProviderObjectName(URI fileUri, String rawDomain, String bucketName) {
String normalizedDomain = normalizeDomain(rawDomain);
if (!StringUtils.hasText(normalizedDomain)) {
return "";
}
URI storageUri;
try {
storageUri = URI.create(normalizedDomain);
} catch (Exception e) {
log.warn("对象存储域名配置无法解析, domain={}", rawDomain, e);
return "";
}
if (!sameAuthority(fileUri, storageUri)) {
return "";
}
String path = stripLeadingSlash(stripQuery(fileUri.getPath()));
String storagePath = stripLeadingSlash(storageUri.getPath());
if (StringUtils.hasText(storagePath) && path.startsWith(storagePath + "/")) {
path = path.substring(storagePath.length() + 1);
}
if (StringUtils.hasText(bucketName) && path.startsWith(bucketName + "/")) {
return path.substring(bucketName.length() + 1);
}
return path;
}
private String extractAliyunHttpObjectName(URI fileUri) {
String pathStyleObjectName = extractHttpProviderObjectName(fileUri, aliyunOssConfig.getEndpoint(), aliyunOssConfig.getBucketName());
if (StringUtils.hasText(pathStyleObjectName)) {
return pathStyleObjectName;
}
if (!StringUtils.hasText(aliyunOssConfig.getBucketName())) {
return "";
}
String normalizedDomain = normalizeDomain(aliyunOssConfig.getEndpoint());
if (!StringUtils.hasText(normalizedDomain)) {
return "";
}
try {
URI endpointUri = URI.create(normalizedDomain);
String expectedHost = aliyunOssConfig.getBucketName() + "." + endpointUri.getHost();
if (fileUri.getHost() != null
&& fileUri.getHost().equalsIgnoreCase(expectedHost)
&& normalizedPort(fileUri) == normalizedPort(endpointUri)) {
return stripLeadingSlash(stripQuery(fileUri.getPath()));
}
return "";
} catch (Exception e) {
log.warn("解析阿里云 OSS 域名配置失败, endpoint={}", aliyunOssConfig.getEndpoint(), e);
return "";
}
}
private String extractAliyunOssObjectName(String ossUrl) {
String value = stripQuery(ossUrl.substring("oss://".length()));
if (!StringUtils.hasText(value)) {
return "";
}
String bucketPrefix = aliyunOssConfig.getBucketName() + "/";
if (StringUtils.hasText(aliyunOssConfig.getBucketName()) && value.startsWith(bucketPrefix)) {
return value.substring(bucketPrefix.length());
}
int slashIndex = value.indexOf('/');
return slashIndex >= 0 ? value.substring(slashIndex + 1) : "";
}
private boolean sameAuthority(URI left, URI right) {
return left.getScheme() != null
&& left.getScheme().equalsIgnoreCase(right.getScheme())
@@ -23,8 +23,10 @@ import com.xiaowang.jayucloud.core.modules.user.dto.*;
import com.xiaowang.jayucloud.core.modules.user.entity.UserDO;
import com.xiaowang.jayucloud.core.modules.user.mapper.UserMapper;
import com.xiaowang.jayucloud.core.modules.file.service.ChunkUploadService;
import com.xiaowang.jayucloud.core.modules.file.service.ObjectStorageFileService;
import com.xiaowang.jayucloud.core.modules.security.support.AdminScopeHelper;
import com.xiaowang.jayucloud.core.modules.file.vo.ChunkUploadSessionVO;
import com.xiaowang.jayucloud.core.modules.file.vo.ObjectStorageFileVO;
import com.xiaowang.jayucloud.core.modules.auth.vo.LoginShopSelectionVO;
import com.xiaowang.jayucloud.core.modules.auth.vo.LoginResponseVO;
import com.xiaowang.jayucloud.core.modules.payment.vo.BalanceChangeDetailVO;
@@ -33,7 +35,6 @@ import com.xiaowang.jayucloud.core.modules.user.vo.UserRelationVO;
import com.xiaowang.jayucloud.core.modules.user.vo.UserVO;
import com.xiaowang.jayucloud.core.modules.user.vo.InviteCodeVO;
import com.xiaowang.jayucloud.core.modules.integration.vo.WechatMiniLoginResultVO;
import com.xiaowang.jayucloud.core.modules.file.service.PrimaryObjectStorageService;
import com.xiaowang.jayucloud.core.modules.user.service.UserAssetService;
import com.xiaowang.jayucloud.core.modules.user.service.UserService;
import com.xiaowang.jayucloud.core.modules.security.service.ShopRoleService;
@@ -94,14 +95,11 @@ public class UserController {
* Variable `userAssetService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final UserAssetService userAssetService;
/**
* Variable `primaryObjectStorageService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final PrimaryObjectStorageService primaryObjectStorageService;
/**
* Variable `chunkUploadService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final ChunkUploadService chunkUploadService;
private final ObjectStorageFileService objectStorageFileService;
/**
* Variable `verificationCodeService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
@@ -770,7 +768,14 @@ public class UserController {
String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
String objectName = "avatar/" + userId + "/" + snowflakeIdGenerator.nextIdString() + fileExtension;
String avatarUrl = primaryObjectStorageService.uploadStream(inputStream, preparedUploadFile.getFileSize(), preparedUploadFile.getContentType(), objectName);
ObjectStorageFileVO fileVO = objectStorageFileService.uploadManagedObjectFile(
originalFilename,
inputStream,
preparedUploadFile.getFileSize(),
preparedUploadFile.getContentType(),
objectName
);
String avatarUrl = fileVO.getPrimaryUrl();
userService.updateUserAvatar(userId, avatarUrl);
chunkUploadService.clearUserAvatarUpload(userId, requestDTO.getUploadId());
return Result.success(objectStorageUrlSupport.toAccessibleUrl(avatarUrl));
@@ -808,7 +813,14 @@ public class UserController {
String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
String objectName = "avatar/" + userId + "/" + snowflakeIdGenerator.nextIdString() + fileExtension;
String avatarUrl = primaryObjectStorageService.uploadFile(file, objectName);
ObjectStorageFileVO fileVO = objectStorageFileService.uploadManagedObjectFile(
originalFilename,
file.getInputStream(),
file.getSize(),
file.getContentType(),
objectName
);
String avatarUrl = fileVO.getPrimaryUrl();
userService.updateUserAvatar(userId, avatarUrl);
return Result.success(objectStorageUrlSupport.toAccessibleUrl(avatarUrl));
@@ -859,9 +871,15 @@ public class UserController {
fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
}
String objectName = "profile/" + userId + "/" + snowflakeIdGenerator.nextIdString() + fileExtension;
String imageUrl = primaryObjectStorageService.uploadStream(inputStream, preparedUploadFile.getFileSize(), preparedUploadFile.getContentType(), objectName);
ObjectStorageFileVO fileVO = objectStorageFileService.uploadManagedObjectFile(
originalFilename,
inputStream,
preparedUploadFile.getFileSize(),
preparedUploadFile.getContentType(),
objectName
);
chunkUploadService.clearUserProfileImageUpload(userId, requestDTO.getUploadId());
return Result.success(objectStorageUrlSupport.toAccessibleUrl(imageUrl));
return Result.success(objectStorageUrlSupport.toAccessibleUrl(fileVO.getPrimaryUrl()));
} catch (Exception e) {
e.printStackTrace();
return Result.error("资料图片上传失败: " + e.getMessage());
@@ -890,8 +908,14 @@ public class UserController {
fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
}
String objectName = "profile/" + userId + "/" + snowflakeIdGenerator.nextIdString() + fileExtension;
String imageUrl = primaryObjectStorageService.uploadFile(file, objectName);
return Result.success(objectStorageUrlSupport.toAccessibleUrl(imageUrl));
ObjectStorageFileVO fileVO = objectStorageFileService.uploadManagedObjectFile(
originalFilename,
file.getInputStream(),
file.getSize(),
file.getContentType(),
objectName
);
return Result.success(objectStorageUrlSupport.toAccessibleUrl(fileVO.getPrimaryUrl()));
} catch (Exception e) {
e.printStackTrace();
return Result.error("资料图片上传失败: " + e.getMessage());
@@ -3,17 +3,26 @@ package com.xiaowang.jayucloud.core.modules.file.service.impl;
import com.xiaowang.jayucloud.core.config.AppCacheProperties;
import com.xiaowang.jayucloud.core.config.ObjectStorageProperties;
import com.xiaowang.jayucloud.core.modules.file.dto.ObjectStorageFileDTO;
import com.xiaowang.jayucloud.core.modules.file.dto.ObjectStorageUploadAttempt;
import com.xiaowang.jayucloud.core.modules.file.dto.ObjectStorageUploadOutcome;
import com.xiaowang.jayucloud.core.modules.file.entity.ObjectStorageFileDO;
import com.xiaowang.jayucloud.core.modules.file.mapper.ObjectStorageFileMapper;
import com.xiaowang.jayucloud.core.modules.file.mq.ObjectStorageBackupMessagePublisher;
import com.xiaowang.jayucloud.core.modules.file.service.ObjectStorageOrchestrationService;
import com.xiaowang.jayucloud.core.modules.file.service.ObjectStorageReplicaService;
import com.xiaowang.jayucloud.core.support.cache.MultiLevelCacheService;
import com.xiaowang.jayucloud.core.modules.file.vo.ObjectStorageFileVO;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.io.ByteArrayInputStream;
import java.time.Duration;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -21,24 +30,29 @@ import static org.mockito.Mockito.when;
class ObjectStorageFileServiceImplTest {
private ObjectStorageFileMapper objectStorageFileMapper;
private MultiLevelCacheService multiLevelCacheService;
private ObjectStorageBackupMessagePublisher objectStorageBackupMessagePublisher;
private ObjectStorageReplicaService objectStorageReplicaService;
private ObjectStorageOrchestrationService objectStorageOrchestrationService;
private ObjectStorageFileServiceImpl service;
@BeforeEach
void setUp() {
objectStorageFileMapper = mock(ObjectStorageFileMapper.class);
MultiLevelCacheService multiLevelCacheService = mock(MultiLevelCacheService.class);
multiLevelCacheService = mock(MultiLevelCacheService.class);
when(multiLevelCacheService.get(any(), any(Duration.class), any())).thenReturn(MultiLevelCacheService.CacheLookup.miss());
AppCacheProperties appCacheProperties = new AppCacheProperties();
objectStorageBackupMessagePublisher = mock(ObjectStorageBackupMessagePublisher.class);
objectStorageReplicaService = mock(ObjectStorageReplicaService.class);
objectStorageOrchestrationService = mock(ObjectStorageOrchestrationService.class);
service = new ObjectStorageFileServiceImpl(
objectStorageFileMapper,
multiLevelCacheService,
appCacheProperties,
objectStorageBackupMessagePublisher,
objectStorageProperties(),
objectStorageReplicaService
objectStorageReplicaService,
objectStorageOrchestrationService
);
}
@@ -76,10 +90,64 @@ class ObjectStorageFileServiceImplTest {
verify(objectStorageBackupMessagePublisher).publish(66L);
}
@Test
void uploadManagedObjectFileUsesConfiguredPrimaryOutcomeAndCreatesReplicaAttempts() throws Exception {
when(objectStorageFileMapper.insert(any(ObjectStorageFileDO.class))).thenAnswer(invocation -> {
ObjectStorageFileDO file = invocation.getArgument(0);
file.setId(77L);
return 1;
});
when(objectStorageFileMapper.selectBatchIds(any())).thenReturn(List.of(storedMinioFile()));
List<ObjectStorageUploadAttempt> attempts = List.of(
new ObjectStorageUploadAttempt("MINIO", "avatar/1/a.png", "http://minio.test/jayucloud/avatar/1/a.png", 1, 0, null)
);
when(objectStorageOrchestrationService.uploadPrimary(any(), eq(3L), eq("image/png"), eq("avatar/1/a.png")))
.thenReturn(new ObjectStorageUploadOutcome("MINIO", "http://minio.test/jayucloud/avatar/1/a.png", attempts));
ObjectStorageFileVO fileVO = service.uploadManagedObjectFile(
"a.png",
new ByteArrayInputStream(new byte[]{1, 2, 3}),
3L,
"image/png",
"avatar/1/a.png"
);
ArgumentCaptor<ObjectStorageFileDO> fileCaptor = ArgumentCaptor.forClass(ObjectStorageFileDO.class);
verify(objectStorageFileMapper).insert(fileCaptor.capture());
ObjectStorageFileDO inserted = fileCaptor.getValue();
assertThat(inserted.getPrimaryProvider()).isEqualTo("MINIO");
assertThat(inserted.getPrimaryUrl()).isEqualTo("http://minio.test/jayucloud/avatar/1/a.png");
assertThat(inserted.getBackupProvider()).isEqualTo("MINIO,QINIU_KODO,ALIYUN_OSS");
verify(objectStorageReplicaService).saveInitialReplicas(77L, attempts);
verify(objectStorageBackupMessagePublisher).publish(77L);
assertThat(fileVO.getId()).isEqualTo(77L);
assertThat(fileVO.getPrimaryProvider()).isEqualTo("MINIO");
}
private ObjectStorageFileDO storedMinioFile() {
ObjectStorageFileDO file = new ObjectStorageFileDO();
file.setId(77L);
file.setFileName("a.png");
file.setFileUrl("http://minio.test/jayucloud/avatar/1/a.png");
file.setObjectName("avatar/1/a.png");
file.setPrimaryProvider("MINIO");
file.setPrimaryUrl("http://minio.test/jayucloud/avatar/1/a.png");
file.setBackupProvider("MINIO,QINIU_KODO,ALIYUN_OSS");
file.setContentType("image/png");
file.setFileSize(3L);
file.setPrimaryUploadStatus(1);
file.setBackupUploadStatus(0);
file.setBackupRetryCount(0);
file.setStatus(1);
return file;
}
private ObjectStorageProperties objectStorageProperties() {
ObjectStorageProperties properties = new ObjectStorageProperties();
properties.setPrimaryProvider("QINIU_KODO");
properties.setBackupProvider("ALIYUN_OSS");
properties.setProviderOrder(List.of("MINIO", "QINIU_KODO", "ALIYUN_OSS"));
properties.setReplicaRequiredProviders(List.of("MINIO", "QINIU_KODO", "ALIYUN_OSS"));
properties.setSignedUrlExpireMinutes(60);
properties.setBackupQueueName("test.queue");
properties.setBackupExchangeName("test.exchange");
@@ -1,10 +1,11 @@
package com.xiaowang.jayucloud.core.modules.file.support;
import com.xiaowang.jayucloud.core.config.ObjectStorageProperties;
import com.xiaowang.jayucloud.core.modules.file.config.AliyunOssConfig;
import com.xiaowang.jayucloud.core.modules.file.config.MinioStorageConfig;
import com.xiaowang.jayucloud.core.modules.file.config.QiniuKodoConfig;
import com.xiaowang.jayucloud.core.modules.file.service.AliyunOssService;
import com.xiaowang.jayucloud.core.modules.file.service.ObjectStorageOrchestrationService;
import com.xiaowang.jayucloud.core.modules.file.service.PrimaryObjectStorageService;
import com.xiaowang.jayucloud.core.modules.file.vo.ObjectStorageFileVO;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -17,14 +18,12 @@ import static org.mockito.Mockito.when;
class ObjectStorageUrlSupportTest {
private PrimaryObjectStorageService primaryObjectStorageService;
private AliyunOssService aliyunOssService;
private ObjectStorageOrchestrationService objectStorageOrchestrationService;
private ObjectStorageUrlSupport support;
@BeforeEach
void setUp() {
primaryObjectStorageService = mock(PrimaryObjectStorageService.class);
aliyunOssService = mock(AliyunOssService.class);
objectStorageOrchestrationService = mock(ObjectStorageOrchestrationService.class);
@@ -32,8 +31,9 @@ class ObjectStorageUrlSupportTest {
qiniuKodoConfig.setDomain("https://cdn.test");
support = new ObjectStorageUrlSupport(
primaryObjectStorageService,
qiniuKodoConfig,
minioStorageConfig(),
aliyunOssConfig(),
aliyunOssService,
objectStorageProperties(),
objectStorageOrchestrationService
@@ -47,7 +47,7 @@ class ObjectStorageUrlSupportTest {
String result = support.toAccessibleUrl(externalUrl);
assertThat(result).isEqualTo(externalUrl);
verifyNoInteractions(primaryObjectStorageService, aliyunOssService, objectStorageOrchestrationService);
verifyNoInteractions(aliyunOssService, objectStorageOrchestrationService);
}
@Test
@@ -61,8 +61,9 @@ class ObjectStorageUrlSupportTest {
qiniuKodoConfig.setDomain("img.example.com");
ObjectStorageUrlSupport urlSupport = new ObjectStorageUrlSupport(
primaryObjectStorageService,
qiniuKodoConfig,
minioStorageConfig(),
aliyunOssConfig(),
aliyunOssService,
objectStorageProperties(),
objectStorageOrchestrationService
@@ -75,6 +76,37 @@ class ObjectStorageUrlSupportTest {
.isEqualTo("http://img.example.com/product/a.jpg?e=1&token=test");
}
@Test
void extractObjectNameSupportsMinioBucketUrl() {
assertThat(support.extractObjectName("http://minio.test:9000/jayucloud/avatar/1/a.png?X-Amz-Signature=1"))
.isEqualTo("avatar/1/a.png");
}
@Test
void extractObjectNameSupportsAliyunOssSchemeUrl() {
assertThat(support.extractObjectName("oss://jayucloud/profile/1/a.png"))
.isEqualTo("profile/1/a.png");
}
@Test
void extractObjectNameSupportsAliyunHttpBucketUrl() {
assertThat(support.extractObjectName("https://oss-cn-hangzhou.aliyuncs.com/jayucloud/profile/1/a.png?x=1"))
.isEqualTo("profile/1/a.png");
}
@Test
void extractObjectNameSupportsAliyunVirtualHostUrl() {
assertThat(support.extractObjectName("https://jayucloud.oss-cn-hangzhou.aliyuncs.com/profile/1/a.png?x=1"))
.isEqualTo("profile/1/a.png");
}
@Test
void toStoredUrlKeepsCurrentProviderUrlInsteadOfRewritingToQiniu() {
String minioUrl = " http://minio.test:9000/jayucloud/avatar/1/a.png ";
assertThat(support.toStoredUrl(minioUrl)).isEqualTo("http://minio.test:9000/jayucloud/avatar/1/a.png");
}
@Test
void toAccessibleUrlReturnsNullInsteadOfRawUrlWhenStringObjectSigningFails() throws Exception {
when(objectStorageOrchestrationService.getPresignedUrl("product/a.jpg", 60))
@@ -150,4 +182,26 @@ class ObjectStorageUrlSupportTest {
properties.setBackupRetryCron("0 0 2 * * ?");
return properties;
}
private MinioStorageConfig minioStorageConfig() {
MinioStorageConfig config = new MinioStorageConfig();
config.setEnabled(true);
config.setEndpoint("http://minio.test:9000");
config.setBucketName("jayucloud");
config.setPrivateBucket(true);
config.setSignedUrlExpireMinutes(60);
return config;
}
private AliyunOssConfig aliyunOssConfig() {
AliyunOssConfig config = new AliyunOssConfig();
config.setEnabled(true);
config.setEndpoint("https://oss-cn-hangzhou.aliyuncs.com");
config.setRegion("cn-hangzhou");
config.setBucketName("jayucloud");
config.setAccessKeyId("test");
config.setAccessKeySecret("test");
config.setSignedUrlExpireMinutes(60);
return config;
}
}
+4
View File
@@ -128,6 +128,10 @@ object-storage:
旧字段 `primary-provider`、`backup-provider` 仅保留兼容展示和旧数据,不再作为三副本调度的唯一事实来源。
新上传入口统一按 `object-storage.provider-order` 选择主存储:第一个可用 Provider 写入 `t_object_storage_file.primary_provider` 和 `primary_url`,`replica-required-providers` 中的其他 Provider 进入副本记录并由备份队列或重试任务补齐。用户头像、个人资料图片、评价图片和通用文件上传都必须走同一条对象存储编排链路;头像和资料图片接口对前端仍返回字符串访问 URL。
历史文件不迁移。展示端会兼容解析旧七牛 URL、新 MinIO bucket URL、阿里云 OSS URL、`oss://bucket/objectName` 和纯 `objectName`,能识别对象存储引用时生成当前可访问签名 URL;无法识别的外部历史 URL 保持原值返回。
#### Nacos 配置归属
`core.yaml` 放业务策略:
+8
View File
@@ -118,3 +118,11 @@
- 处理方式:调整 `MessageHubClientServiceImpl` 的 SPUG 模板参数组装逻辑,让设计师端和店务端 SPUG 短信均携带 `name`、`code`、`number`;同步更新 `MessageHubClientServiceImplTest` 和运维配置说明中的店务端 SPUG 模板参数说明。
- 影响范围:仅影响 JY-Core 通过 MessageHub SPUG 通道发送短信验证码时的模板参数;不修改通道 ID、来源系统 token、数据库结构和初始化 SQL。
- 验证方式:运行 `MessageHubClientServiceImplTest`,覆盖店务端 SPUG 模板 `SPUG_SMS_VERIFY_3` 请求体包含 `templateParams.name`。
## 2026-07-12 文件上传统一对象存储编排链路
- 变更原因:用户确认所有文件相关上传都必须根据对象存储配置选择统一主存储,例如 `MINIO` 排第一时先写 MinIO,其他启用 Provider 作为副本补齐;此前头像、资料图片和评价图片仍可能绕过统一编排直接调用旧主存储。
- 处理方式:新增 `ObjectStorageFileService.uploadManagedObjectFile`,集中完成主存储上传、文件建档、初始副本记录和备份消息触发;通用文件上传、头像上传、资料图片上传和评价图片上传统一调用该方法。
- URL 兼容:`ObjectStorageUrlSupport` 支持旧七牛 URL、新 MinIO bucket URL、阿里云 OSS URL、`oss://bucket/objectName` 和纯 `objectName`;头像和资料图片接口仍返回字符串访问 URL,不改变前端接口形态。
- 影响范围:JY-Core 文件、用户和评价图片上传链路;不迁移历史文件,不修改数据库结构,不修改初始化 SQL。
- 验证方式:运行 `ObjectStorageFileServiceImplTest` 和 `ObjectStorageUrlSupportTest`,覆盖 MinIO 主 provider 建档、副本 attempts 保存、MinIO/OSS/Qiniu/objectName URL 解析和历史外部 URL 回退。