在日常开发中,对象存储的集成总让人头疼?本文通过完整可运行的Java代码,手把手教你实现RustFS的实时上传下载功能,带你彻底告别集成难题!
目录
一、环境准备:5分钟快速搭建RustFS服务
1.1 Docker一键启动RustFS
首先使用Docker快速搭建RustFS服务环境:
# 创建项目目录
mkdir rustfs-java-demo && cd rustfs-java-demo
# 创建docker-compose.yml
cat > docker-compose.yml << 'EOF'
version: '3.8'
services:
rustfs:
image: rustfs/rustfs:latest
container_name: rustfs-server
ports:
- "9000:9000" # S3 API端口
- "9001:9001" # 控制台端口
environment:
RUSTFS_ACCESS_KEY: "admin"
RUSTFS_SECRET_KEY: "password123"
volumes:
- ./data:/data
restart: unless-stopped
EOF
# 启动服务
docker-compose up -d
# 验证服务状态
docker ps | grep rustfs
1.2 验证服务可用性
# 检查服务健康状态
curl http://localhost:9000/minio/health/live
# 访问Web控制台
echo "控制台地址: http://localhost:9001"
echo "用户名: admin"
echo "密码: password123"
二、Java项目配置:依赖引入与客户端初始化
2.1 Maven依赖配置
创建Spring Boot项目,在pom.xml中添加必要依赖:
<dependencies>
<!-- Spring Boot Starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- AWS S3 SDK -->
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>s3</artifactId>
<version>2.20.0</version>
</dependency>
<!-- 文件操作工具 -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.13.0</version>
</dependency>
</dependencies>
2.2 RustFS配置类
创建配置类RustFSConfig.java:
package com.rustfs.demo.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import java.net.URI;
@Configuration
public class RustFSConfig {
@Value("${rustfs.endpoint:http://localhost:9000}")
private String endpoint;
@Value("${rustfs.access-key:admin}")
private String accessKey;
@Value("${rustfs.secret-key:password123}")
private String secretKey;
@Value("${rustfs.region:us-east-1}")
private String region;
@Bean
public S3Client s3Client() {
return S3Client.builder()
.endpointOverride(URI.create(endpoint))
.credentialsProvider(StaticCredentialsProvider.create(
AwsBasicCredentials.create(accessKey, secretKey)))
.region(Region.of(region))
.forcePathStyle(true) // 必须设置为true用于兼容RustFS
.build();
}
}
2.3 应用配置文件
application.yml配置:
rustfs:
endpoint: "http://localhost:9000"
access-key: "admin"
secret-key: "password123"
region: "us-east-1"
bucket-name: "my-bucket"
server:
port: 8080
spring:
servlet:
multipart:
max-file-size: 10MB
max-request-size: 10MB
三、核心服务层:上传下载功能实现
3.1 存储服务接口设计
创建StorageService.java接口:
package com.rustfs.demo.service;
import org.springframework.web.multipart.MultipartFile;
import java.io.InputStream;
public interface StorageService {
/**
* 上传文件到RustFS
*/
String uploadFile(MultipartFile file, String objectName);
/**
* 下载文件从RustFS
*/
InputStream downloadFile(String objectName);
/**
* 获取文件访问URL
*/
String getFileUrl(String objectName);
/**
* 删除文件
*/
boolean deleteFile(String objectName);
}
3.2 RustFS服务实现类
实现类RustFSService.java:
package com.rustfs.demo.service.impl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.*;
import java.io.IOException;
import java.io.InputStream;
import java.time.Duration;
@Service
@Slf4j
public class RustFSService implements StorageService {
private final S3Client s3Client;
@Value("${rustfs.bucket-name:my-bucket}")
private String bucketName;
public RustFSService(S3Client s3Client) {
this.s3Client = s3Client;
createBucketIfNotExists();
}
/**
* 检查并创建存储桶
*/
private void createBucketIfNotExists() {
try {
s3Client.headBucket(HeadBucketRequest.builder()
.bucket(bucketName)
.build());
log.info("存储桶 {} 已存在", bucketName);
} catch (NoSuchBucketException e) {
// 存储桶不存在,创建新桶
s3Client.createBucket(CreateBucketRequest.builder()
.bucket(bucketName)
.build());
log.info("创建存储桶: {}", bucketName);
}
}
@Override
public String uploadFile(MultipartFile file, String objectName) {
try {
// 如果未指定对象名称,使用原始文件名
if (objectName == null || objectName.trim().isEmpty()) {
objectName = file.getOriginalFilename();
}
// 执行文件上传
PutObjectRequest putObjectRequest = PutObjectRequest.builder()
.bucket(bucketName)
.key(objectName)
.contentType(file.getContentType())
.build();
s3Client.putObject(putObjectRequest,
RequestBody.fromBytes(file.getBytes()));
log.info("文件上传成功: {}", objectName);
return objectName;
} catch (IOException e) {
log.error("文件上传失败: {}", e.getMessage());
throw new RuntimeException("文件上传失败", e);
}
}
@Override
public InputStream downloadFile(String objectName) {
try {
GetObjectRequest getObjectRequest = GetObjectRequest.builder()
.bucket(bucketName)
.key(objectName)
.build();
return s3Client.getObject(getObjectRequest);
} catch (NoSuchKeyException e) {
log.error("文件不存在: {}", objectName);
throw new RuntimeException("文件不存在: " + objectName);
}
}
@Override
public String getFileUrl(String objectName) {
try {
GetUrlRequest getUrlRequest = GetUrlRequest.builder()
.bucket(bucketName)
.key(objectName)
.build();
return s3Client.utilities().getUrl(getUrlRequest).toString();
} catch (Exception e) {
log.error("获取文件URL失败: {}", e.getMessage());
return null;
}
}
@Override
public boolean deleteFile(String objectName) {
try {
DeleteObjectRequest deleteObjectRequest = DeleteObjectRequest.builder()
.bucket(bucketName)
.key(objectName)
.build();
s3Client.deleteObject(deleteObjectRequest);
log.info("文件删除成功: {}", objectName);
return true;
} catch (Exception e) {
log.error("文件删除失败: {}", e.getMessage());
return false;
}
}
}
四、RESTful API控制器:提供HTTP接口
4.1 文件上传下载控制器
创建FileController.java:
package com.rustfs.demo.controller;
import com.rustfs.demo.service.StorageService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
@RestController
@RequestMapping("/api/files")
@Slf4j
public class FileController {
private final StorageService storageService;
public FileController(StorageService storageService) {
this.storageService = storageService;
}
/**
* 文件上传接口
*/
@PostMapping("/upload")
public ResponseEntity<Map<String, Object>> uploadFile(
@RequestParam("file") MultipartFile file,
@RequestParam(value = "objectName", required = false) String objectName) {
try {
String uploadedObjectName = storageService.uploadFile(file, objectName);
String fileUrl = storageService.getFileUrl(uploadedObjectName);
Map<String, Object> result = new HashMap<>();
result.put("success", true);
result.put("objectName", uploadedObjectName);
result.put("fileUrl", fileUrl);
result.put("fileSize", file.getSize());
result.put("message", "文件上传成功");
return ResponseEntity.ok(result);
} catch (Exception e) {
log.error("文件上传失败: {}", e.getMessage());
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(Map.of("success", false, "message", "文件上传失败: " + e.getMessage()));
}
}
/**
* 文件下载接口
*/
@GetMapping("/download/{objectName}")
public ResponseEntity<byte[]> downloadFile(@PathVariable String objectName) {
try {
InputStream inputStream = storageService.downloadFile(objectName);
byte[] fileBytes = IOUtils.toByteArray(inputStream);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentDispositionFormData("attachment",
new String(objectName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));
return new ResponseEntity<>(fileBytes, headers, HttpStatus.OK);
} catch (Exception e) {
log.error("文件下载失败: {}", e.getMessage());
return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
}
}
/**
* 获取文件信息
*/
@GetMapping("/info/{objectName}")
public ResponseEntity<Map<String, Object>> getFileInfo(@PathVariable String objectName) {
try {
String fileUrl = storageService.getFileUrl(objectName);
Map<String, Object> result = new HashMap<>();
result.put("objectName", objectName);
result.put("fileUrl", fileUrl);
result.put("exists", true);
return ResponseEntity.ok(result);
} catch (Exception e) {
return ResponseEntity.ok(Map.of(
"objectName", objectName,
"exists", false,
"message", "文件不存在"
));
}
}
/**
* 删除文件接口
*/
@DeleteMapping("/{objectName}")
public ResponseEntity<Map<String, Object>> deleteFile(@PathVariable String objectName) {
try {
boolean success = storageService.deleteFile(objectName);
Map<String, Object> result = new HashMap<>();
result.put("success", success);
result.put("message", success ? "文件删除成功" : "文件删除失败");
return ResponseEntity.ok(result);
} catch (Exception e) {
log.error("文件删除失败: {}", e.getMessage());
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(Map.of("success", false, "message", "文件删除失败"));
}
}
}
五、高级功能:大文件分片上传
5.1 分片上传服务类
对于大文件,实现分片上传功能:
package com.rustfs.demo.service.impl;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.*;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
@Service
public class MultipartUploadService {
private final S3Client s3Client;
private static final int PART_SIZE = 5 * 1024 * 1024; // 5MB
public MultipartUploadService(S3Client s3Client) {
this.s3Client = s3Client;
}
/**
* 大文件分片上传
*/
public String uploadLargeFile(MultipartFile file, String bucketName, String objectName)
throws Exception {
// 初始化分片上传
CreateMultipartUploadRequest createRequest = CreateMultipartUploadRequest.builder()
.bucket(bucketName)
.key(objectName)
.contentType(file.getContentType())
.build();
CreateMultipartUploadResponse createResponse = s3Client.createMultipartUpload(createRequest);
String uploadId = createResponse.uploadId();
List<CompletedPart> completedParts = new ArrayList<>();
byte[] fileBytes = file.getBytes();
int partCount = (int) Math.ceil((double) fileBytes.length / PART_SIZE);
// 上传各个分片
for (int partNumber = 1; partNumber <= partCount; partNumber++) {
int start = (partNumber - 1) * PART_SIZE;
int end = Math.min(start + PART_SIZE, fileBytes.length);
byte[] partBytes = new byte[end - start];
System.arraycopy(fileBytes, start, partBytes, 0, partBytes.length);
UploadPartRequest uploadRequest = UploadPartRequest.builder()
.bucket(bucketName)
.key(objectName)
.uploadId(uploadId)
.partNumber(partNumber)
.build();
UploadPartResponse uploadResponse = s3Client.uploadPart(uploadRequest,
RequestBody.fromBytes(partBytes));
completedParts.add(CompletedPart.builder()
.partNumber(partNumber)
.eTag(uploadResponse.eTag())
.build());
}
// 完成分片上传
CompletedMultipartUpload completedMultipartUpload = CompletedMultipartUpload.builder()
.parts(completedParts)
.build();
CompleteMultipartUploadRequest completeRequest = CompleteMultipartUploadRequest.builder()
.bucket(bucketName)
.key(objectName)
.uploadId(uploadId)
.multipartUpload(completedMultipartUpload)
.build();
s3Client.completeMultipartUpload(completeRequest);
return objectName;
}
}
六、功能测试与验证
6.1 使用curl测试API接口
# 测试文件上传
curl -X POST -F "file=@test.jpg" \
http://localhost:8080/api/files/upload
# 测试文件下载
curl -X GET \
http://localhost:8080/api/files/download/test.jpg \
--output downloaded.jpg
# 测试文件信息查询
curl -X GET \
http://localhost:8080/api/files/info/test.jpg
# 测试文件删除
curl -X DELETE \
http://localhost:8080/api/files/test.jpg
6.2 使用Postman测试
创建测试集合,包含以下请求:
-
POST
/api/files/upload- 文件上传 -
GET
/api/files/download/{name}- 文件下载 -
GET
/api/files/info/{name}- 文件信息 -
DELETE
/api/files/{name}- 文件删除
七、生产环境优化建议
7.1 连接池配置优化
@Bean
public S3Client s3Client() {
return S3Client.builder()
.endpointOverride(URI.create(endpoint))
.credentialsProvider(StaticCredentialsProvider.create(
AwsBasicCredentials.create(accessKey, secretKey)))
.region(Region.of(region))
.forcePathStyle(true)
.httpClientBuilder(UrlConnectionHttpClient.builder()
.maxConnections(100) // 最大连接数
.connectionTimeout(Duration.ofSeconds(10)) // 连接超时
.socketTimeout(Duration.ofSeconds(30))) // 读写超时
.build();
}
7.2 异常处理增强
创建全局异常处理器:
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(S3Exception.class)
public ResponseEntity<Map<String, Object>> handleS3Exception(S3Exception e) {
log.error("RustFS操作异常: {}", e.getMessage());
Map<String, Object> error = new HashMap<>();
error.put("success", false);
error.put("errorCode", e.awsErrorDetails().errorCode());
error.put("message", "存储服务异常: " + e.getMessage());
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
}
}
八、完整项目结构
src/main/java/
└── com/rustfs/demo/
├── config/
│ └── RustFSConfig.java
├── controller/
│ └── FileController.java
├── service/
│ ├── StorageService.java
│ ├── impl/
│ │ ├── RustFSService.java
│ │ └── MultipartUploadService.java
│ └── exception/
│ └── GlobalExceptionHandler.java
└── DemoApplication.java
总结
通过本文的完整实现,我们成功构建了一个基于Java和Docker的RustFS文件存储服务。关键亮点包括:
✅ 开箱即用:提供完整可运行的代码示例
✅ 功能全面:覆盖上传、下载、删除等核心操作
✅ 生产就绪:包含异常处理、性能优化等生产级特性
✅ 易于扩展:模块化设计便于功能扩展
这种实现方式特别适合需要快速集成对象存储功能的Java项目,无论是单体应用还是微服务架构都能良好适配。
以下是深入学习 RustFS 的推荐资源:RustFS
官方文档: RustFS 官方文档- 提供架构、安装指南和 API 参考。
GitHub 仓库: GitHub 仓库 - 获取源代码、提交问题或贡献代码。
社区支持: GitHub Discussions- 与开发者交流经验和解决方案。
966

被折叠的 条评论
为什么被折叠?



