关于Java项目使用MinIO存储对象服务的解决方案
最近公司项目需要改造升级,将原先存储在数据库中的文件对象改为从文件服务器中获取,最终决定使用MinIO来存储业务中的文件,MinIO平台支持多个存储桶以及海量对象,这为数据备份和容灾提供了极大的便利。这种设计确保了系统具备卓越的可用性和稳定性,从而保障了业务连续性。其轻量级特性并不繁复,因此出现故障的几率极低,展示出卓越的稳定性。此外,MinIO的集群搭建过程简单易行,而且提供了一系列的SDK。总体来说,MinIO文件存储在各种场景下都能够提供高效、稳定、安全的数据存储服务。
这里来记一下具体使用方法。
-
第一步,先引入
MinIo
的依赖,这里以8.3.4版本为例。<dependency> <groupId>io.minio</groupId> <artifactId>minio</artifactId> <version>8.3.4</version> </dependency>
然后配置MinIo服务的地址,用户名密码,一般会写在配置文件
yml
里
minio:
url: http://localhost:8848
accessKey: admin
secretKey: admin
MinIo
的配置类,这里附带几个MinIo常用的判断文件是否存在以及上传获取的方法。这里的地址一般都是写在配置文件里,SpringBoot
项目中可以使用@Value
注解获取配置文件中的值。
@Slf4j
@Configuration
public class MinioUtils {
@Value("${minio.url}")
private String endpoint;
@Value("${minio.accessKey}")
private String accessKey;
@Value("${minio.secretKey}")
private String secretKey;
// 桶名
private String bucketName = "testBucket";
private static MinioClient minioClient;
@Bean
public MinioClient getMinioClient() {
MinioClient minioClient = null;
try {
minioClient = MinioClient.builder().endpoint(endpoint).credentials(accessKey, secretKey).build();
} catch (Exception e) {
log.error("连接MinIO服务器异常:{}", e);
}
return minioClient;
}
@PostConstruct
public void setMinioClient() {
try {
minioClient = MinioClient.builder().endpoint(endpoint).credentials(accessKey, secretKey).build();
} catch (Exception e) {
log.error("连接MinIO服务器异常:{}", e);
}
}
/**
* 判断文件是否存在
*
* @param bucketName 存储桶
* @param objectName 对象
* @return true:存在
*/
public static boolean doesObjectExist(String bucketName, String objectName) {
boolean exist = true;
try {
minioClient.statObject(StatObjectArgs.builder().bucket(bucketName).object(objectName).build());
} catch (Exception e) {
exist = false;
}
return exist;
}
/**
* 获取文件流
*
* @param bucketName bucket名称
* @param objectName 文件名称
* @return 二进制流
*/
public static InputStream getObject(String bucketName, String objectName) throws Exception {
return minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(objectName).build());
}
/**
* 流式上传文件
* @param inputStream 流
* @param newFileName 文件名(这里可以包含路径用 / 拼接)
*/
public Map<String,Object> uploadInputStream(InputStream inputStream,String newFileName) throws Exception {
Map<String,Object> map = new HashMap<String, Object>();
try {
minioClient.putObject(PutObjectArgs.builder().bucket(bucketName).object(newFileName)
.stream(inputStream, inputStream.available(), -1).build());
//文件名称
map.put("objectName", newFileName);
//桶名称
map.put("bucket", bucketName);
} catch (Exception e) {
map = null;
log.error(e.getMessage(),e);
}
return map;
}
}
大家在使用过程有什么问题可以评论或私信我啊,我会第一时间帮大家解答的!!!