1、参考
MinIO对象存储介绍和使用
【备忘录】JAVASDK连接MinIO,附完整代码
2、
package org.j****g.common.util.io;
import cn.hutool.core.io.FileUtil;
import io.minio.*;
import io.minio.errors.MinioException;
import io.minio.http.Method;
import io.minio.messages.Bucket;
import io.minio.messages.DeleteError;
import io.minio.messages.DeleteObject;
import io.minio.messages.Item;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.j****g.common.util.CN;
import org.j****g.common.util.DateUtils;
import org.j****g.common.util.network.RedisUtil;
import org.j****g.common.util.spring.SpringContextUtils;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
@Slf4j
public class MinIoUtil {
public static void main(String[] args) throws Exception {
File file = new File("C:\\Users\\e******0\\Desktop\\桌面文件\\测试图 横版01.png");
String objectName = "img/" + file.getName();
// MinIoUtil.putObjectByStream(bucketName, objectName, new FileInputStream(file));
//
// MinIoUtil.removeObject(objectName);
//
// GetObjectResponse response = MinIoUtil.getObject(objectName);
// File file_dest = new File("C:\\Users\\e******0\\Desktop\\桌面文件\\测试图 横版02.png");
// FileUtil.writeFromStream(response, file_dest);
String availableFileUrl = MinIoUtil.getAvailableFileUrl(objectName);
System.out.println("======availableFileUrl\n" + availableFileUrl);
}
private static MinioClient minioClient;
private static String bucketName;
static {
try {
MinIoConfig minIoConfig = new MinIoConfig("http://127.0.0.1:9000", "minioadmin", "minioadmin", "j****g");
init(minIoConfig);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void init(MinIoConfig minIoConfig) throws Exception {
bucketName = minIoConfig.getBucketName();
minioClient = MinioClient.builder()
.endpoint(minIoConfig.getEndpoint())
.credentials(minIoConfig.getAccessKey(), minIoConfig.getSecretKey())
.build();
// 初始化Bucket
initBucket();
log.info("成功连接上minio.URL:{} ,bucket {}", minIoConfig.getEndpoint(), bucketName);
}
private static void initBucket() throws Exception {
// 应用启动时检测Bucket是否存在
boolean found = doesBucketExist(bucketName);
// 如果Bucket不存在,则创建Bucket
if (!found) {
minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
log.info("成功创建 Bucket [{}]", bucketName);
}
}
/* ------------------------------------> 快速启动 <------------------------------------------------ */
/**
* 上传文件
*
* @param is 输入流
* @param object 对象(文件)名
* @param contentType 文件类型
*/
public static void putObject(InputStream is, String object, String contentType) throws Exception {
long start = System.currentTimeMillis();
minioClient.putObject(PutObjectArgs.builder()
.bucket(bucketName)
.object(object)
.contentType(contentType)
.stream(is, -1, 1024 * 1024 * 10) // 不得小于 5 Mib
.build());
log.info("成功上传文件至云端 [{}],耗时 [{} ms]", object, System.currentTimeMillis() - start);
}
/**
* 获取文件流
*
* @param object 对象(文件)名
* @return 文件流
*/
public static GetObjectResponse getObject(String object) throws Exception {
long start = System.currentTimeMillis();
GetObjectResponse response = minioClient.getObject(GetObjectArgs.builder()
.bucket(bucketName)
.object(object)
.build());
log.info("成功获取 Object [{}],耗时 [{} ms]", object, System.currentTimeMillis() - start);
return response;
}
/**
* 删除对象(文件)
*
* @param object 对象(文件名)
*/
public static void removeObject(String object) throws Exception {
minioClient.removeObject(RemoveObjectArgs.builder()
.bucket(bucketName)
.object(object)
.build());
log.info("成功删除 Object [{}]", object);
}
/* ------------------------------------> 快速启动 end <------------------------------------------------ */
/* ------------------------------------> 桶相关的操作 <------------------------------------------------ */
/**
* 创建桶
*
* @param bucketName bucket名称
* @throws MinioException minio异常
*/
public static void createBucket(String bucketName) throws MinioException {
try {
if (!minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build())) {
minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
}
} catch (Exception e) {
log.error("minio 异常 {} ", e);
throw new MinioException("create Bucket error!");
}
}
/**
* 判断桶是否存在
*
* @param bucketName 存储桶
* @return true:存在
*/
public static boolean doesBucketExist(String bucketName) throws MinioException {
try {
return minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
} catch (Exception e) {
log.error("minio 异常 {} ", e);
throw new MinioException("does Bucket Exist error!");
}
}
/**
* 获取桶策略
*
* @param bucketName bucket名称
* @return {@link String}
* @throws MinioException s3minio异常
*/
public static String getBucketPolicy(String bucketName) throws MinioException {
try {
return minioClient.getBucketPolicy(GetBucketPolicyArgs.builder().bucket(bucketName).build());
} catch (Exception e) {
log.error("minio 异常 {} ", e);
throw new MinioException("get Bucket Policy error!!");
}
}
/**
* 获取所有桶
*
* @return {@link List}<{@link Bucket}>
* @throws MinioException s3minio异常
*/
public static List<Bucket> getAllBuckets() throws MinioException {
try {
return minioClient.listBuckets();
} catch (Exception e) {
log.error("minio 异常 {} ", e);
throw new MinioException("get All Buckets error");
}
}
/**
* 获取桶信息
*
* @param bucketName bucket名称
* @return {@link Optional}<{@link Bucket}>
* @throws MinioException s3minio异常
*/
public static Optional<Bucket> getBucketInfo(String bucketName) throws MinioException {
try {
return getAllBuckets().stream().filter(b -> b.name().equals(bucketName)).findFirst();
} catch (Exception e) {
log.error("minio 异常 {} ", e);
throw new MinioException("get Buckets Info error");
}
}
/**
* 删除桶
*
* @param bucketName bucket名称
* @throws MinioException s3minio异常
*/
public static void removeBucket(String bucketName) throws MinioException {
try {
minioClient.removeBucket(RemoveBucketArgs.builder().bucket(bucketName).build());
} catch (Exception e) {
log.error("minio 异常 {} ", e);
throw new MinioException("remove Bucket error!!");
}
}
/* ------------------------------------> 桶相关的操作 end <------------------------------------------------ */
/* ------------------------------------> 文件管理相关 start <------------------------------------------------ */
/**
* 判断文件夹是否存在
*
* @param bucketName 存储桶
* @param folderName 文件夹名称(去掉/)
* @return true:存在
*/
public static boolean folderExist(String bucketName, String folderName) throws MinioException {
boolean exist = false;
try {
Iterable<Result<Item>> results = minioClient.listObjects(
ListObjectsArgs.builder().bucket(bucketName).prefix(folderName).recursive(false).build());
for (Result<Item> result : results) {
Item item = result.get();
if (item.isDir() && folderName.equals(item.objectName())) {
exist = true;
}
}
} catch (Exception e) {
log.error("minio 异常 {} ", e);
throw new MinioException("folderExist error!");
}
return exist;
}
/**
* 判断对象是否存在
*
* @param bucketName bucket名称
* @param objectName 对象名称
* @return boolean
*/
public static boolean objectExist(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 对象名称
* @param expires 过期时间 秒
* @return {@link String}
* @throws MinioException s3minio异常
*/
public static String getObjectUrl(String bucketName, String objectName, Integer expires) throws MinioException {
try {
return minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs
.builder().bucket(bucketName).object(objectName).expiry(expires).method(Method.GET).build());
} catch (Exception e) {
log.error("minio 异常 {} ", e);
throw new MinioException("获取文件外链异常");
}
}
/**
* 获取文件外链(1天过期
*
* @param bucketName bucket名称
* @param objectName 对象名称
* @return {@link String}
* @throws MinioException s3minio异常
*/
public static String getObjectUrl(String bucketName, String objectName) throws MinioException {
try {
return minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs
.builder().bucket(bucketName).object(objectName).expiry(24 * 60 * 60).method(Method.GET).build());
} catch (Exception e) {
log.error("minio 异常 {} ", e);
throw new MinioException("获取文件外链异常");
}
}
/**
* 获取对象
*
* @param bucketName bucket名称
* @param objectName 对象名称
* @return {@link GetObjectResponse} 文件流
* @throws MinioException s3minio异常
*/
public static GetObjectResponse getObject(String bucketName, String objectName) throws MinioException {
try {
return minioClient.getObject(GetObjectArgs.builder()
.bucket(bucketName)
.object(objectName)
.build());
} catch (Exception e) {
log.error("minio 异常 {} ", e);
throw new MinioException("获取对象异常");
}
}
/**
* 获取对象信息
*
* @param bucketName bucket名称
* @param objectName 对象名称
* @return {@link StatObjectResponse}
* @throws MinioException s3minio异常
*/
public static StatObjectResponse getObjectInfo(String bucketName, String objectName) throws MinioException {
try {
return minioClient.statObject(
StatObjectArgs.builder().bucket(bucketName).object(objectName).build());
} catch (Exception e) {
log.error("minio 异常 {} ", e);
throw new MinioException("获取对象信息异常");
}
}
/**
* 获取对象 (断点下载)
*
* @param bucketName bucket名称
* @param objectName 对象名称
* @param offset 起始字节位置
* @param length 读取长度
* @return {@link GetObjectResponse}
* @throws Exception 异常
*/
public static GetObjectResponse getObject(String bucketName, String objectName, long offset, long length) throws MinioException {
try {
return minioClient.getObject(
GetObjectArgs.builder().bucket(bucketName).object(objectName).offset(offset).length(length).build());
} catch (Exception e) {
log.error("minio 异常 {} ", e);
throw new MinioException("断点下载异常");
}
}
/**
* 通过MultipartFile上传文件
*
* @param bucketName 存储桶
* @param file 文件
* @param objectName 对象名
*/
public static ObjectWriteResponse putObject(String bucketName, MultipartFile file, String objectName, String contentType) throws MinioException {
try (InputStream inputStream = file.getInputStream()) {
return minioClient.putObject(
PutObjectArgs.builder().bucket(bucketName).object(objectName).contentType(contentType)
.stream(inputStream, inputStream.available(), -1).build());
} catch (Exception e) {
log.error("minio 异常 {} ", e);
throw new MinioException("文件上传异常");
}
}
/**
* 上传本地文件
*
* @param bucketName 存储桶
* @param objectName 对象名称
* @param fileName 本地文件路径
*/
public static ObjectWriteResponse putObject(String bucketName, String objectName, String fileName) throws MinioException {
try {
return minioClient.uploadObject(UploadObjectArgs.builder()
.bucket(bucketName).object(objectName).filename(fileName).build());
} catch (Exception e) {
log.error("minio 异常 {} ", e);
throw new MinioException("上传本地文件异常");
}
}
/**
* 通过流上传文件
*
* @param bucketName 存储桶
* @param objectName 文件对象
* @param inputStream 文件流
*/
public static ObjectWriteResponse putObjectByStream(String bucketName, String objectName, InputStream inputStream) throws MinioException {
try {
return minioClient.putObject(
PutObjectArgs.builder().bucket(bucketName).object(objectName).stream(inputStream, inputStream.available(), -1)
.build());
} catch (Exception e) {
log.error("minio 异常 {} ", e);
throw new MinioException("通过流上传文件异常");
}
}
/**
* 创建文件夹或目录
*
* @param bucketName 存储桶
* @param objectName 目录路径
*/
public static ObjectWriteResponse createFolder(String bucketName, String objectName) throws MinioException {
try {
return minioClient.putObject(
PutObjectArgs.builder().bucket(bucketName).object(objectName).stream(
new ByteArrayInputStream(new byte[]{}), 0, -1)
.build());
} catch (Exception e) {
log.error("minio 异常 {} ", e);
throw new MinioException("文件夹创建异常");
}
}
/**
* 拷贝文件
*
* @param bucketName 存储桶
* @param objectName 文件名
* @param srcBucketName 目标存储桶
* @param srcObjectName 目标文件名
*/
public static ObjectWriteResponse copyObject(String bucketName, String objectName, String srcBucketName, String srcObjectName) throws MinioException {
try {
return minioClient.copyObject(
CopyObjectArgs.builder()
.source(CopySource.builder().bucket(bucketName).object(objectName).build())
.bucket(srcBucketName)
.object(srcObjectName)
.build());
} catch (Exception e) {
log.error("minio 异常 {} ", e);
throw new MinioException("拷贝文件 异常");
}
}
/**
* 删除文件
*
* @param bucketName 存储桶
* @param objectName 文件名称
*/
public static void removeObject(String bucketName, String objectName) throws MinioException {
try {
minioClient.removeObject(
RemoveObjectArgs.builder()
.bucket(bucketName)
.object(objectName)
.build());
} catch (Exception e) {
log.error("minio 异常 {} ", e);
throw new MinioException("删除文件 异常");
}
}
/**
* 批量删除对象
*
* @param bucketName bucket名称
* @param objectsName 对象名字
* @return {@link Iterable}<{@link Result}<{@link DeleteError}>>
* @throws MinioException s3minio异常
*/
public static Iterable<Result<DeleteError>> removeObjects(String bucketName, List<String> objectsName) throws MinioException {
try {
Iterable<Result<DeleteError>> results = minioClient.removeObjects(RemoveObjectsArgs.builder().bucket(bucketName)
.objects(objectsName.stream().map(DeleteObject::new).collect(Collectors.toList())).build());
return results;
} catch (Exception e) {
log.error("minio 异常 {} ", e);
throw new MinioException("批量删除对象 异常");
}
}
/**
* 批量删除对象2
*
* @param bucketName bucket名称
* @param objectName 对象名字
* @return {@link Iterable}<{@link Result}<{@link DeleteError}>>
* @throws MinioException s3minio异常
*/
public static Iterable<Result<DeleteError>> removeObjects(String bucketName, String... objectName) throws MinioException {
try {
Iterable<Result<DeleteError>> results = minioClient.removeObjects(RemoveObjectsArgs.builder().bucket(bucketName)
.objects(Arrays.stream(objectName).map(DeleteObject::new).collect(Collectors.toList())).build());
return results;
} catch (Exception e) {
log.error("minio 异常 {} ", e);
throw new MinioException("批量删除对象 异常");
}
}
/**
* 获取文件路径的 可访问链接
*/
public static String getAvailableFileUrl(String objectName) {
if (CN.isEmpty(objectName) || objectName.startsWith("http"))
return objectName;
String cc;
try {
RedisUtil redisUtil = SpringContextUtils.getBean(RedisUtil.class);
String redisKey = "minio_" + objectName;
boolean hasRedisUtil = redisUtil != null;
if (hasRedisUtil && redisUtil.hasKey(redisKey)) {
return redisUtil.getStr(redisKey);
}
int expires = 60 * 60 * 24 * 7 - 100;
cc = getObjectUrl(bucketName, objectName, expires);
if (hasRedisUtil) {
redisUtil.set(redisKey, cc, expires);
}
} catch (Exception e) {
String str = DateUtils.getNowStrForLogPre() + " 【getAvailableFileUrl 获取文件路径的 可访问链接 异常】 " + e.getMessage();
System.out.println(str);
log.error(str, e);
cc = objectName;
}
return cc;
}
@Data
@NoArgsConstructor
@Configuration
@Component
@ConfigurationProperties(prefix = "j****g.minio")
public static class MinIoConfig {
private String endpoint;
private String accessKey;
private String secretKey;
private String bucketName;
public MinIoConfig(String endpoint, String accessKey, String secretKey, String bucketName) {
this.endpoint = endpoint;
this.accessKey = accessKey;
this.secretKey = secretKey;
this.bucketName = bucketName;
}
}
}
标签:调用,java,String,objectName,param,bucketName,MinioException,throws,MinIO
From: https://www.cnblogs.com/kikyoqiang/p/18184414