以下是一个Spring Boot应用程序,集成MinIO实现文件存储和查询的示例。我们将使用MinIO提供的Java SDK来与MinIO进行交互。
docker compose 安装 MinIO
使用docker compose 安装并启动 MinIO:
minIO-compose.yml 文件内容:
version: '3.5'
services:
minio:
container_name: milvus-minio
image: minio/minio:latest
environment:
MINIO_ACCESS_KEY: minioadmin
MINIO_SECRET_KEY: minioadmin
ports:
- "9001:9001"
- "9000:9000"
volumes:
- ${DOCKER_VOLUME_DIRECTORY:-.}/volumes/minio:/minio_data
command: minio server /minio_data --console-address ":9001"
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:9000/minio/health/live"]
interval: 30s
timeout: 20s
retries: 3
启动容器:
docker compose -f minIO-compose.yml up -d
创建Spring Boot项目
首先,确保你在项目的pom.xml
文件中添加了以下依赖:
<dependencies>
<!-- Spring Boot Starter Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- MinIO Java SDK -->
<dependency>
<groupId>io.minio</groupId>
<artifactId>minio</artifactId>
<version>8.2.2</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-compress</artifactId>
<version>1.21</version>
</dependency>
<!-- Lombok (可选) -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.26</version>
<scope>provided</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>2.3.12.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
配置MinIO连接
在application.properties
文件中添加MinIO相关的配置:
minio.url=http://localhost:9000
minio.access-key=minioadmin
minio.secret-key=minioadmin
minio.bucket-name=mybucket
创建配置类
创建一个配置类来定义MinioClient:
package com.example.miniodemo.config;
import io.minio.MinioClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MinioConfig {
@Value("${minio.url}")
private String minioUrl;
@Value("${minio.access-key}")
private String accessKey;
@Value("${minio.secret-key}")
private String secretKey;
@Bean
public MinioClient minioClient() {
return MinioClient.builder()
.endpoint(minioUrl)
.credentials(accessKey, secretKey)
.build();
}
}
创建服务层
创建一个服务层来封装业务逻辑:
package com.example.miniodemo.service;
import io.minio.*;
import io.minio.errors.*;
import io.minio.messages.Bucket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.InputStream;
import java.util.List;
@Service
public class MinioService {
@Autowired
private MinioClient minioClient;
@Value("${minio.bucket-name}")
private String bucketName;
public void createBucket() throws Exception {
boolean isExist = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
if (!isExist) {
minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
}
}
public String uploadFile(MultipartFile file) throws Exception {
String fileName = file.getOriginalFilename();
InputStream inputStream = file.getInputStream();
minioClient.putObject(
PutObjectArgs.builder().bucket(bucketName).object(fileName).stream(
inputStream, file.getSize(), -1)
.contentType(file.getContentType())
.build());
return fileName;
}
public InputStream downloadFile(String fileName) throws Exception {
return minioClient.getObject(
GetObjectArgs.builder()
.bucket(bucketName)
.object(fileName)
.build());
}
public List<Bucket> listBuckets() throws Exception {
return minioClient.listBuckets();
}
}
创建控制器
创建一个控制器来处理HTTP请求:
package com.example.miniodemo.controller;
import com.example.miniodemo.service.MinioService;
import io.minio.messages.Bucket;
import org.apache.commons.compress.utils.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
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.util.List;
@RestController
@RequestMapping("/minio")
public class MinioController {
@Autowired
private MinioService minioService;
@PostMapping("/create-bucket")
public String createBucket() throws Exception {
minioService.createBucket();
return "Bucket created successfully!";
}
@PostMapping("/upload")
public String uploadFile(@RequestParam("file") MultipartFile file) throws Exception {
return minioService.uploadFile(file);
}
@GetMapping("/download/{fileName}")
public ResponseEntity<byte[]> downloadFile(@PathVariable String fileName) throws Exception {
InputStream inputStream = minioService.downloadFile(fileName);
byte[] bytes = IOUtils.toByteArray(inputStream);
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"")
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.body(bytes);
}
@GetMapping("/list-buckets")
public List<Bucket> listBuckets() throws Exception {
return minioService.listBuckets();
}
}
Spring Boot 主类
创建Spring Boot应用程序的主类:
package com.example.miniodemo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MinioDemoApplication {
public static void main(String[] args) {
SpringApplication.run(MinioDemoApplication.class, args);
}
}
运行应用程序
启动Spring Boot应用程序。你可以使用Postman或其他HTTP客户端来测试API:
-
创建桶:
POST http://localhost:8080/minio/create-bucket
-
上传文件:
POST http://localhost:8080/minio/upload Form-Data: - Key: file - Value: (选择一个文件)
-
下载文件:
GET http://localhost:8080/minio/download/{fileName}
-
列出所有桶:
GET http://localhost:8080/minio/list-buckets
解释
-
依赖管理:
- 使用Spring Boot Starter Web简化Web应用开发。
- 使用MinIO Java SDK来与MinIO对象存储服务器进行交互。
-
配置:
- 在
application.properties
中指定MinIO服务器的地址、访问密钥和桶名称。
- 在
-
配置类:
- 定义MinioClient bean用于与MinIO进行交互。
-
服务层:
- 封装业务逻辑,提供创建桶、上传文件、下载文件和列出所有桶的高层接口。
-
控制器:
- 处理HTTP请求,提供RESTful API进行文件存储和查询。
通过这个示例,你可以轻松地使用Spring Boot集成MinIO来实现文件的存储和查询功能。