要在Spring Boot项目中使用MinIO作为对象存储服务,可以使用MinIO的Java SDK来与MinIO进行交互。以下是如何在Spring Boot应用中配置和使用MinIO的详细步骤:
1. 添加MinIO依赖
首先,你需要在项目中添加MinIO的Java SDK依赖。如果使用的是Maven,添加以下依赖到pom.xml
中:
<dependency>
<groupId>io.minio</groupId>
<artifactId>minio</artifactId>
<version>8.2.0</version> <!-- 使用最新的稳定版本 -->
</dependency>
如果使用的是Gradle,添加以下依赖到build.gradle
中:
implementation 'io.minio:minio:8.2.0' // 使用最新的稳定版本
2. 配置MinIO客户端
可以通过Spring Boot的配置文件application.properties
或application.yml
来配置MinIO客户端的连接信息。
示例:application.yml
spring:
# 文件上传
servlet:
multipart:
# 单个文件大小
max-file-size: 10MB
# 设置总上传的文件大小
max-request-size: 20MB
minio:
endpoint: http://localhost:9000 # MinIO服务器的URL
access-key: minioadmin # 访问密钥
secret-key: minioadmin # 密钥密码
bucket-name: works # 默认的Bucket名称
secure: false # 是否使用HTTPS(如果使用HTTPS,请设置为true)
3. 创建MinIO配置类
接下来,创建一个配置类来初始化MinIO客户端,并将其作为Spring Bean进行管理。
MinIO配置类
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix = "minio")
@Data
public class MinioProperties {
private String endpoint;
private String accessKey;
private String secretKey;
private String bucketName;
private String secure;
}
import io.minio.MinioClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableConfigurationProperties(MinioProperties.class)
public class MinioConfiguration {
@Autowired
private MinioProperties properties;
@Bean
public MinioClient minioClient() {
return MinioClient.builder().endpoint(properties.getEndpoint()).credentials(properties.getAccessKey(), properties.getSecretKey()).build();
}
}
4. 使用MinIO客户端
现在你可以在你的服务或控制器中使用MinIO客户端来执行各种操作,例如上传、下载、列举对象等。
接口类
import io.minio.errors.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
public interface FileService {
String upload(MultipartFile file) throws ServerException,
InsufficientDataException, ErrorResponseException,
IOException, NoSuchAlgorithmException, InvalidKeyException,
InvalidResponseException, XmlParserException, InternalException;
}
实现类
import com.echo.common.minio.MinioProperties;
import com.echo.webapp.file.service.FileService;
import io.minio.*;
import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
@Service
public class FileServiceImpl implements FileService {
@Autowired
private MinioProperties properties;
@Autowired
private MinioClient minioClient;
@Override
public String upload(MultipartFile file) throws ServerException,
InsufficientDataException, ErrorResponseException, IOException,
NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException,
XmlParserException, InternalException {
boolean bucketExists = minioClient.bucketExists(
BucketExistsArgs.builder()
.bucket(properties.getBucketName())
.build());
if (!bucketExists) {
minioClient.makeBucket(
MakeBucketArgs.builder()
.bucket(properties.getBucketName())
.build());
minioClient.setBucketPolicy(
SetBucketPolicyArgs.builder()
.bucket(properties.getBucketName())
.config(createBucketPolicyConfig(properties.getBucketName()))
.build());
}
String filename = new SimpleDateFormat("yyyyMMdd").format(new Date()) +
"/" + UUID.randomUUID() + "-" + file.getOriginalFilename();
minioClient.putObject(
PutObjectArgs.builder()
.bucket(properties.getBucketName())
.stream(file.getInputStream(), file.getSize(), -1)
.object(filename)
.contentType(file.getContentType())
.build());
return String.join("/", properties.getEndpoint(), properties.getBucketName(), filename);
}
private String createBucketPolicyConfig(String bucketName) {
return """
{
"Statement" : [ {
"Action" : "s3:GetObject",
"Effect" : "Allow",
"Principal" : "*",
"Resource" : "arn:aws:s3:::%s/*"
} ],
"Version" : "2012-10-17"
}
""".formatted(bucketName);
}
}
控制类
import com.echo.common.result.Result;
import com.echo.webapp.file.service.FileService;
import io.minio.errors.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
@Tag(name = "文件管理")
@RequestMapping("/app/file")
@RestController
public class FileUploadController {
@Autowired
private FileService fileService;
@Operation(summary = "上传文件")
@PostMapping("upload")
public Result<String> upload(@RequestPart MultipartFile file) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
String url = fileService.upload(file);
return Result.ok(url);
}
}