获取服务器配置文件的值
@Value("${bpm.minio.bucketName:}")
private String minioBarrel;

获取nacos 配置文件的值
package com.guodi.bpm.common.minio;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix = "bpm.minio")
public class MinioProperties {
private String endpoint;
private String accessKey;
private String secretKey;
private String bucketName;
public String getEndpoint() {
return endpoint;
}
public void setEndpoint(String endpoint) {
this.endpoint = endpoint;
}
public String getAccessKey() {
return accessKey;
}
public void setAccessKey(String accessKey) {
this.accessKey = accessKey;
}
public String getSecretKey() {
return secretKey;
}
public void setSecretKey(String secretKey) {
this.secretKey = secretKey;
}
public String getBucketName() {
return bucketName;
}
public void setBucketName(String bucketName) {
this.bucketName = bucketName;
}
}
package com.guodi.bpm.service.impl;
import com.guodi.bpm.common.auth.secure.utils.FileUtil;
import com.guodi.bpm.common.auth.secure.utils.Func;
import com.guodi.bpm.common.auth.secure.utils.StringPool;
import com.guodi.bpm.common.auth.secure.utils.StringUtil;
import com.guodi.bpm.common.minio.MinioException;
import com.guodi.bpm.common.minio.MinioProperties;
import com.guodi.bpm.common.minio.model.MinioFile;
import com.guodi.bpm.common.minio.model.StorageObject;
import com.guodi.bpm.service.IFileService;
import io.minio.*;
import io.minio.messages.Item;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.util.CollectionUtils;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.sql.Date;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
@EnableConfigurationProperties({MinioProperties.class})
public class MinIOFileServiceImpl implements IFileService {
private static final Logger LOGGER = LoggerFactory.getLogger(MinIOFileServiceImpl.class);
public static final String DEFAULT_ENCODED = "UTF-8";
private final String bucketName;
private final MinioClient minioClient;
private final String endpoint;
public MinIOFileServiceImpl(MinioProperties minioProperties) {
this.minioClient = this.getMinioClient(minioProperties);
this.bucketName = minioProperties.getBucketName();
this.endpoint = minioProperties.getEndpoint();
}
public MinioClient getMinioClient(MinioProperties minioProperties) {
String endpoint = minioProperties.getEndpoint();
String accesskey = minioProperties.getAccessKey();
String secretkey = minioProperties.getSecretKey();
String bucketName = minioProperties.getBucketName();
if (endpoint == null || "".equals(endpoint)) {
throw new MinioException("Minio的URL未在application.yml配置!");
}
if (accesskey == null || "".equals(accesskey)) {
throw new MinioException("Minio用户名未在application.yml配置!");
}
if (secretkey == null || "".equals(secretkey)) {
throw new MinioException("Minio密码未在application.yml配置!");
}
if ((bucketName == null || "".equals(bucketName))) {
throw new MinioException("存储桶名称未在application.yml配置!");
}
MinioClient minioClient =
MinioClient.builder()
.endpoint(endpoint)
.credentials(accesskey, secretkey)
.build();
makeBucket(minioClient, bucketName);
return minioClient;
}
private void makeBucket(MinioClient minioClient, String bucketName) {
try {
boolean isExist = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
if (!isExist) {
minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
String policyJson =
"{\n" +
" \"Statement\": [\n" +
" {\n" +
" \"Action\": [\n" +
" \"s3:GetBucketLocation\",\n" +
" \"s3:ListBucket\"\n" +
" ],\n" +
" \"Effect\": \"Allow\",\n" +
" \"Principal\": \"*\",\n" +
" \"Resource\": \"arn:aws:s3:::" + bucketName + "\"\n" +
" },\n" +
" {\n" +
" \"Action\": [\n" +
" \"s3:GetObject\",\n" +
" \"s3:PutObject\"\n" +
" ],\n" +
" \"Effect\": \"Allow\",\n" +
" \"Principal\": \"*\",\n" +
" \"Resource\": \"arn:aws:s3:::" + bucketName + "/*\"\n" +
" }\n" +
" ],\n" +
" \"Version\": \"2012-10-17\"\n" +
" }";
minioClient.setBucketPolicy(
SetBucketPolicyArgs.builder().bucket(bucketName).config(policyJson).build());
}
} catch (Exception e) {
throw new MinioException("创建minio存储桶异常", e);
}
}
@Override
public String putObject(String objectName, InputStream inputStream) {
if ((objectName == null || "".equals(objectName))) {
throw new MinioException("存储对象名称objectName不能为空!");
}
try {
minioClient.putObject(
PutObjectArgs.builder().bucket(bucketName).object(objectName).stream(
inputStream, -1, 10485760)
.build());
LOGGER.info("文件上传成功!");
return URLDecoder.decode(this.getObjectUrl(objectName), "utf-8");
} catch (Exception e) {
throw new MinioException(e.getMessage(), e);
}
}
@Override
public InputStream getObject(String objectName) {
InputStream inputStream = null;
try {
inputStream = minioClient.getObject(
GetObjectArgs.builder()
.bucket(bucketName)
.object(objectName)
.build());
} catch (Exception e) {
throw new MinioException("minio获取储存对象路径不存在!", e.getCause());
}
return inputStream;
}
@Override
public Long getFileSize(String fileUrl) {
Long fileSize = 0L;
try {
if (fileUrl.indexOf(bucketName) != -1) {
fileUrl = StringUtil.sub(fileUrl,
fileUrl.indexOf(bucketName) + bucketName.length(), -1);
}
MinioFile minioFile = this.getMinioFile(fileUrl);
if (minioFile != null) {
fileSize = minioFile.getLength();
}
} catch (Exception e) {
e.printStackTrace();
LOGGER.error("下载发生错误: {}!", e.getMessage());
return fileSize;
}
return fileSize;
}
@Override
public void getObject(String objectName, OutputStream outputStream) {
InputStream is = getObject(objectName);
Optional.ofNullable(is).ifPresent(inputStream -> {
try {
byte[] buffer = new byte[2048];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, len);
}
outputStream.flush();
} catch (Exception e) {
throw new MinioException(e.getMessage(), e);
}
});
}
@Override
public List<StorageObject> listObjects(String objectPrefix) throws MinioException {
List<StorageObject> storageObjects = new ArrayList<>();
try {
Iterable<Result<Item>> objects = minioClient.listObjects(
ListObjectsArgs.builder()
.bucket(bucketName)
.prefix(objectPrefix)
.recursive(true)
.build()
);
for (Result<Item> itemResult : objects) {
Item item = itemResult.get();
StorageObject storageObject = new StorageObject();
storageObject.setBucketName(bucketName);
storageObject.setObjectName(item.objectName());
storageObjects.add(storageObject);
}
} catch (Exception e) {
throw new MinioException(e.getMessage(), e);
}
return storageObjects;
}
@Override
public void removeObject(String objectName) {
try {
minioClient.removeObject(RemoveObjectArgs.builder().bucket(bucketName).object(objectName).build());
} catch (Exception e) {
throw new MinioException(e.getMessage(), e);
}
}
@Override
public void removeByFileUrl(String fileUrl) {
try {
String downloadUrl = fileUrl.substring(fileUrl.indexOf(bucketName) + bucketName.length());
minioClient.removeObject(RemoveObjectArgs.builder().bucket(bucketName).object(downloadUrl).build());
} catch (Exception e) {
throw new MinioException(e.getMessage(), e);
}
}
@Override
public void removeObjectBatch(Collection<String> objectNames) {
if (!CollectionUtils.isEmpty(objectNames)) {
objectNames.forEach(objectName -> {
this.removeObject(objectName);
});
}
}
@Override
public void downloadObject(String objectName, String fileName) {
try {
minioClient.downloadObject(
DownloadObjectArgs.builder()
.bucket(bucketName)
.object(objectName)
.filename(fileName).build());
} catch (Exception e) {
throw new MinioException(e.getMessage(), e);
}
}
@Override
public String getObjectUrl(String objectName) {
try {
return minioClient.getObjectUrl(bucketName, objectName);
} catch (Exception e) {
throw new MinioException(e.getMessage(), e);
}
}
private MinioFile getMinioFile(String objectName) {
MinioFile minoFile = new MinioFile();
try {
ObjectStat stat = minioClient.statObject(StatObjectArgs.builder().bucket(bucketName).object(objectName).build());
String name = Func.isEmpty(stat.name()) ? StringUtil.sub(objectName, objectName.lastIndexOf("/") + 1
, objectName.length()) : StringUtil.sub(stat.name(), stat.name().lastIndexOf("/") + 1
, stat.name().length());
minoFile.setName(name);
minoFile.setLink(fileLink(stat.name()));
minoFile.setHash(String.valueOf(stat.hashCode()));
minoFile.setLength(stat.length());
minoFile.setPutTime(Date.from(stat.createdTime().toInstant()));
minoFile.setContentType(stat.contentType());
minoFile.setSuffix(name.substring(name.lastIndexOf(".") + 1));
} catch (Exception e) {
LOGGER.error("读取存储对象异常", e);
throw new MinioException("读取存储对象异常", e);
}
return minoFile;
}
@Override
public String fileLink(String fileName) {
return StringPool.SLASH.concat(bucketName).concat(StringPool.SLASH).concat(fileName);
}
@Override
public String formatLink(String link) {
if (StringUtil.isBlank(link)) {
return null;
}
if (link.indexOf(endpoint) != -1) {
link = StringUtil.sub(link, link.indexOf(endpoint) + endpoint
.length());
}
try {
link = FileUtil.formatUrl(link);
link = URLDecoder.decode(link, DEFAULT_ENCODED);
} catch (UnsupportedEncodingException e) {
LOGGER.error(e.getMessage());
}
return link;
}
@Override
public String getBucketName() {
return bucketName;
}
}
