引入Maven依赖
<dependency>
<groupId>io.miniogroupId>
<artifactId>minioartifactId>
<version>8.3.0version>
dependency>
配置文件
minio:
url: http://192.168.1.222:7901/
accessKey: minio
secretKey: minio@123
bucket: test
配置文件实体类
@Data
@Validated
@Component
@ConfigurationProperties(prefix = "minio")
public class MinioProperties {
@NotEmpty(message = "minio服务地址不可为空")
@URL(message = "minio服务地址格式错误")
private String url;
@NotEmpty(message = "minio认证账户不可为空")
private String accessKey;
@NotEmpty(message = "minio认证密码不可为空")
private String secretKey;
private String bucket;
private boolean createBucket = true;
private boolean checkBucket = true;
private long connectTimeout;
private long writeTimeout;
private long readTimeout;
}
Springboot启动类
@EnableBladeFeign
@SpringCloudApplication
@ConditionalOnClass(MinioClient.class)
@Slf4j
public class ControlApplication {
public static void main(String[] args) {
BladeApplication.run(LauncherConstant.APPLICATION_CONTROL_NAME, ControlApplication.class, args);
}
@Resource
private MinioProperties minioAutoProperties;
@Bean
public MinioClient minioClient() {
log.info("开始初始化MinioClient, url为{}, accessKey为:{}", minioAutoProperties.getUrl(), minioAutoProperties.getAccessKey());
MinioClient minioClient = MinioClient
.builder()
.endpoint(minioAutoProperties.getUrl())
.credentials(minioAutoProperties.getAccessKey(), minioAutoProperties.getSecretKey())
.build();
minioClient.setTimeout(
minioAutoProperties.getConnectTimeout(),
minioAutoProperties.getWriteTimeout(),
minioAutoProperties.getReadTimeout()
);
if (minioAutoProperties.isCheckBucket()) {
log.info("checkBucket为{}, 开始检测桶是否存在", minioAutoProperties.isCheckBucket());
String bucketName = minioAutoProperties.getBucket();
if (!checkBucket(bucketName, minioClient)) {
log.info("文件桶[{}]不存在, 开始检查是否可以新建桶", bucketName);
if (minioAutoProperties.isCreateBucket()) {
log.info("createBucket为{},开始新建文件桶", minioAutoProperties.isCreateBucket());
createBucket(bucketName, minioClient);
}
}
log.info("文件桶[{}]已存在, minio客户端连接成功!", bucketName);
} else {
throw new RuntimeException("桶不存在, 请检查桶名称是否正确或者将checkBucket属性改为false");
}
return minioClient;
}
private boolean checkBucket(String bucketName, MinioClient minioClient) {
boolean isExists = false;
try {
isExists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
} catch (Exception e) {
throw new RuntimeException("failed to check if the bucket exists", e);
}
return isExists;
}
private void createBucket(String bucketName, MinioClient minioClient) {
try {
minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
log.info("文件桶[{}]新建成功, minio客户端已连接", bucketName);
} catch (Exception e) {
throw new RuntimeException("failed to create default bucket", e);
}
}
}
Minio 工具类
package org.springblade.control.config;
import io.minio.*;
import io.minio.messages.Bucket;
import io.minio.messages.Item;
import lombok.SneakyThrows;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.io.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.function.IntFunction;
@Component
public class MinioUtils {
@Resource
private MinioClient minioClient;
@Resource
private MinioProperties minioProperties;
public Boolean bucketExists(String bucketName) {
try {
return minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
} catch (Exception e) {
throw new RuntimeException("检查桶是否存在失败!", e);
}
}
public void createBucket(String bucketName) {
if (!this.bucketExists(bucketName)) {
try {
minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
} catch (Exception e) {
throw new RuntimeException("创建桶失败!", e);
}
}
}
public String putObject(MultipartFile file) {
String fileName = getFileName(Objects.requireNonNull(file.getOriginalFilename()));
this.putMultipartFile(minioProperties.getBucket(), fileName, file);
return minioProperties.getUrl() + "/" + minioProperties.getBucket() + "/" + fileName;
}
public String putObject(String objectName, InputStream stream, String contentType) {
String fileName = getFileName(objectName);
this.putInputStream(minioProperties.getBucket(), fileName, stream, contentType);
return minioProperties.getUrl() + "/" + minioProperties.getBucket() + "/" + fileName;
}
public String putObject(String objectName, byte[] bytes, String contentType) {
String fileName = getFileName(objectName);
this.putBytes(minioProperties.getBucket(), fileName, bytes, contentType);
return minioProperties.getUrl() + "/" + minioProperties.getBucket() + "/" + fileName;
}
public String putObject(String objectName, MultipartFile file) {
objectName = getFileName(objectName);
this.putMultipartFile(minioProperties.getBucket(), objectName, file);
return minioProperties.getUrl() + "/" + minioProperties.getBucket() + "/" + objectName;
}
public String putObject(String bucketName, String objectName, MultipartFile file) {
this.createBucket(bucketName);
objectName = getFileName(objectName);
this.putMultipartFile(bucketName, objectName, file);
return minioProperties.getUrl() + "/" + bucketName + "/" + objectName;
}
public String putObject(String bucketName, String objectName, InputStream stream, String contentType) {
this.createBucket(bucketName);
String fileName = getFileName(objectName);
this.putInputStream(bucketName, fileName, stream, contentType);
return minioProperties.getUrl() + "/" + bucketName + "/" + fileName;
}
public String putObject(String bucketName, String objectName, byte[] bytes, String contentType) {
this.createBucket(bucketName);
String fileName = getFileName(objectName);
this.putBytes(bucketName, fileName, bytes, contentType);
return minioProperties.getUrl() + "/" + bucketName + "/" + fileName;
}
public String putObject(String objectName, File file, String contentType) {
String fileName = getFileName(objectName);
this.putFile(minioProperties.getBucket(), fileName, file, contentType);
return minioProperties.getUrl() + "/" + minioProperties.getBucket() + "/" + fileName;
}
public String putObject(String bucketName, String objectName, File file, String contentType) {
this.createBucket(bucketName);
String fileName = getFileName(objectName);
this.putFile(bucketName, fileName, file, contentType);
return minioProperties.getUrl() + "/" + bucketName + "/" + fileName;
}
public Boolean checkFileIsExist(String objectName) {
return this.checkFileIsExist(minioProperties.getBucket(), objectName);
}
public Boolean checkFolderIsExist(String folderName) {
return this.checkFolderIsExist(minioProperties.getBucket(), folderName);
}
public Boolean checkFileIsExist(String bucketName, String objectName) {
try {
minioClient.statObject(
StatObjectArgs.builder().bucket(bucketName).object(objectName).build()
);
} catch (Exception e) {
return false;
}
return true;
}
public Boolean checkFolderIsExist(String bucketName, String folderName) {
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())) {
return true;
}
}
} catch (Exception e) {
return false;
}
return true;
}
public InputStream getObject(String objectName) {
return this.getObject(minioProperties.getBucket(), objectName);
}
public InputStream getObject(String bucketName, String objectName) {
try {
return minioClient
.getObject(GetObjectArgs.builder().bucket(bucketName).object(objectName).build());
} catch (Exception e) {
throw new RuntimeException("根据文件名获取流失败!", e);
}
}
public InputStream getObjectByUrl(String url) {
try {
return new URL(url).openStream();
} catch (IOException e) {
throw new RuntimeException("根据URL获取流失败!", e);
}
}
public List<Bucket> getAllBuckets() {
try {
return minioClient.listBuckets();
} catch (Exception e) {
throw new RuntimeException("获取全部存储桶失败!", e);
}
}
public Optional<Bucket> getBucket(String bucketName) {
try {
return minioClient.listBuckets().stream().filter(b -> b.name().equals(bucketName)).findFirst();
} catch (Exception e) {
throw new RuntimeException("根据存储桶名称获取信息失败!", e);
}
}
public void removeBucket(String bucketName) {
try {
minioClient.removeBucket(RemoveBucketArgs.builder().bucket(bucketName).build());
} catch (Exception e) {
throw new RuntimeException("根据存储桶名称删除桶失败!", e);
}
}
public boolean removeObject(String objectName) {
try {
this.removeObject(minioProperties.getBucket(), objectName);
} catch (Exception e) {
return false;
}
return true;
}
public boolean removeObject(String bucketName, String objectName) {
try {
minioClient.removeObject(RemoveObjectArgs.builder().bucket(bucketName).object(objectName).build());
} catch (Exception e) {
return false;
}
return true;
}
private void putMultipartFile(String bucketName, String objectName, MultipartFile file) {
InputStream stream = null;
try {
stream = file.getInputStream();
} catch (IOException e) {
throw new RuntimeException("文件流获取错误", e);
}
try {
minioClient.putObject(
PutObjectArgs.builder()
.bucket(bucketName)
.object(objectName)
.contentType(file.getContentType())
.stream(stream, stream.available(), -1)
.build()
);
} catch (Exception e) {
throw new RuntimeException("文件流上传错误", e);
}
}
private void putInputStream(String bucketName, String objectName, InputStream stream, String contentType) {
try {
minioClient.putObject(
PutObjectArgs.builder()
.bucket(bucketName)
.object(objectName)
.contentType(contentType)
.stream(stream, stream.available(), -1)
.build()
);
} catch (Exception e) {
throw new RuntimeException("文件流上传错误", e);
}
}
private void putBytes(String bucketName, String objectName, byte[] bytes, String contentType) {
InputStream stream = new ByteArrayInputStream(bytes);
try {
minioClient.putObject(
PutObjectArgs.builder()
.bucket(bucketName)
.object(objectName)
.contentType(contentType)
.stream(stream, stream.available(), -1)
.build()
);
} catch (Exception e) {
throw new RuntimeException("文件流上传错误", e);
}
}
private void putFile(String bucketName, String objectName, File file, String contentType) {
try {
FileInputStream fileInputStream = new FileInputStream(file);
minioClient.putObject(
PutObjectArgs.builder()
.bucket(bucketName)
.object(objectName)
.contentType(contentType)
.stream(fileInputStream, fileInputStream.available(), -1)
.build()
);
} catch (Exception e) {
throw new RuntimeException("文件上传错误", e);
}
}
private static String getFileName(String objectName) {
int lastIndexOf = objectName.lastIndexOf(".");
if (lastIndexOf == -1) {
return String.format("%s_%s", objectName, System.currentTimeMillis());
} else {
String filePrefix = objectName.substring(0, objectName.lastIndexOf("."));
String fileSuffix = objectName.substring(objectName.lastIndexOf(".") + 1);
return String.format("%s_%s.%s", filePrefix, System.currentTimeMillis(), fileSuffix);
}
}
public StatObjectResponse getObjectInfo(String bucketName, String objectName) throws Exception {
return minioClient.statObject(StatObjectArgs.builder().bucket(bucketName).object(objectName).build());
}
@SneakyThrows
public String getObjectURL(String bucketName, String objectName, Integer expires) {
IntFunction<Integer> integerIntFunction = (int i) -> {
return Math.min(i, 7);
};
return minioClient.getPresignedObjectUrl(
GetPresignedObjectUrlArgs.builder()
.bucket(bucketName)
.object(objectName)
.expiry(integerIntFunction.apply(expires))
.build());
}
@SneakyThrows
public List<Item> getAllObjectsByPrefix(String bucketName, String prefix, boolean recursive) {
List<Item> list = new ArrayList<>();
Iterable<Result<Item>> objectsIterator = minioClient.listObjects(
ListObjectsArgs.builder().bucket(bucketName).prefix(prefix)
.recursive(recursive).build()
);
if (objectsIterator != null) {
for (Result<Item> result : objectsIterator) {
Item item = result.get();
list.add(item);
}
}
return list;
}
}