SpringBoot整合Minio
0. 前置:部署Minio
这是基于
Docker
来部署Minio, 拉取Minio
镜像
docker pull minio/minio
创建网络
docker network create minio-net
创建Minio容器并运行
docker run --name minio --restart=always \
-p 9000:9000 -p 9090:9090 \
--net=minio-net \
-e "MINIO_ROOT_USER=minio" \
-e "MINIO_ROOT_PASSWORD=minioAdmin" \
-v /data/minio/data:/data \
-v /data/minio/conf:/root/.minio \
-d minio/minio server \
/data --console-address ":9090" -address ":9000"
访问 xxx.xxx.xxx.xxx:9090, 服务器地址+端口号
创建一个Bucket, Bucket名字要在配置文件上使用, 然后设置权限为可见
1. 引入依赖
前提:已经在本地启动或服务器部署
Minio
服务
<minio.version>8.5.7</minio.version>
<!-- MinIO 依赖配置 -->
<dependency>
<groupId>io.minio</groupId>
<artifactId>minio</artifactId>
<version>${minio.version}</version>
</dependency>
2. 编写配置文件
# 对象存储配置
oss:
# MinIO OSS配置
minio:
# 是否开启(预先关闭)
enable: true
# 域名(格式:【ip:port】)
endpoint: 159.xxx.xxx.xxx:9000
# 用户的 RootUser
rootUser: minio
# 用户的 RootPassword
rootPassword: minioAdmin
# 是否开启TLS
enable-tls: false
# 桶名称
bucket-name: public
编写相关配置文件的代码
OssMinioCondition
/**
* MinIO自定义配置条件
*
* @author Ccoo
*/
public class OssMinioCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
String property = context.getEnvironment().getProperty("oss.minio.enable");
return StringUtils.equals("true", property);
}
}
MinioProperties
/**
* Minio配置属性
*
* @author Ccoo
*/
@Data
@ConfigurationProperties(prefix = "oss.minio")
public class MinioProperties {
/**
* 是否开启
*/
private Boolean enable = false;
/**
* 域名(一定是协议前缀+ip+port)
*/
private String endpoint;
/**
* 是否开启TLS
*/
private Boolean enableTls = false;
/**
* 用户的 AccessKey
*/
private String rootUser;
/**
* 用户的 SecretKey
*/
private String rootPassword;
/**
* 桶名称
*/
private String bucketName;
}
MinioConfiguration
/**
* MinIO配置
*
* @author Ccoo
*/
@Slf4j
@Configuration
@AllArgsConstructor
@Conditional(OssMinioCondition.class)
@EnableConfigurationProperties(MinioProperties.class)
public class MinioConfiguration {
private final MinioProperties minioProperties;
/**
* 上传文件到MinIO
*
* @param file 待上传的文件
* @param rootPath 上传的路径
* @return 文件所在路径
*/
public String uploadToMinio(MultipartFile file, String rootPath) {
// http://159.xxx.xxx.xxx:9000/public/rootPath/8991891fa872440a93cf3c9a7d8e7f5d1712931544483.jpeg
MinioClient minioClient = getMinioClient();
String key;
InputStream inputStream = null;
try {
if (file == null) {
throw new CustomizeFileException(ReturnCode.USER_DO_NOT_UPLOAD_FILE);
}
String originalName = StringUtils.isNotBlank(file.getOriginalFilename()) ? file.getOriginalFilename() : file.getName();
String suffix = FilenameUtils.getExtension(originalName);
if (StringUtils.isEmpty(suffix)) {
suffix = "." + Constantes.UNKNOWN_FILE_TYPE_SUFFIX;
} else {
suffix = "." + suffix;
}
// 创建一个随机文件名称
String fileName = UUID.randomUUID().toString().replaceAll("-", "") + System.currentTimeMillis() + suffix;
// 对象键(Key)是对象在存储桶中的唯一标识。
key = StringUtils.isBlank(StringUtils.trim(rootPath)) ? fileName : rootPath + "/" + fileName;
inputStream = file.getInputStream();
minioClient.putObject(PutObjectArgs.builder()
.bucket(minioProperties.getBucketName())
.object(key)
.stream(inputStream, inputStream.available(), 5 * 1024 * 1024).build());
} catch (Exception e) {
e.printStackTrace();
throw new CustomizeFileException(ReturnCode.FILE_UPLOAD_EXCEPTION);
} finally {
IOUtils.closeQuietly(inputStream);
}
return (minioProperties.getEnableTls() ? Constantes.HTTPS : Constantes.HTTP)
+ minioProperties.getEndpoint() + "/" + minioProperties.getBucketName() + "/" + key;
}
/**
* 上传文件到MinIO
*
* @param inputStream 待上传的文件流
* @param suffix 文件后缀
* @param rootPath 上传的路径
* @return 文件所在路径
*/
public String uploadToMinio(InputStream inputStream, String suffix, String rootPath) {
MinioClient minioClient = getMinioClient();
String key;
try {
if (ObjectUtils.isEmpty(inputStream)) {
throw new CustomizeFileException(ReturnCode.USER_DO_NOT_UPLOAD_FILE);
}
if (StringUtils.isEmpty(suffix)) {
suffix = "." + Constantes.UNKNOWN_FILE_TYPE_SUFFIX;
} else {
suffix = "." + suffix;
}
// 创建一个随机文件名称
String fileName = UUID.randomUUID().toString().replaceAll("-", "") + System.currentTimeMillis() + suffix;
// 对象键(Key)是对象在存储桶中的唯一标识。
key = StringUtils.isBlank(StringUtils.trim(rootPath)) ? fileName : rootPath + "/" + fileName;
minioClient.putObject(PutObjectArgs.builder()
.bucket(minioProperties.getBucketName())
.object(key)
.stream(inputStream, inputStream.available(), 5 * 1024 * 1024).build());
} catch (Exception e) {
e.printStackTrace();
throw new CustomizeFileException(ReturnCode.FILE_UPLOAD_EXCEPTION);
} finally {
IOUtils.closeQuietly(inputStream);
}
return (minioProperties.getEnableTls() ? Constantes.HTTPS : Constantes.HTTP)
+ minioProperties.getEndpoint() + "/" + minioProperties.getBucketName() + "/" + key;
}
public String uploadToMinio(byte[] bytes, String suffix, String rootPath) {
MinioClient minioClient = getMinioClient();
String key;
InputStream inputStream = null;
try {
if (ObjectUtils.isEmpty(bytes)) {
throw new CustomizeFileException(ReturnCode.USER_DO_NOT_UPLOAD_FILE);
}
inputStream = new ByteArrayInputStream(bytes);
if (StringUtils.isEmpty(suffix)) {
suffix = "." + Constantes.UNKNOWN_FILE_TYPE_SUFFIX;
} else {
suffix = "." + suffix;
}
// 创建一个随机文件名称
String fileName = UUID.randomUUID().toString().replaceAll("-", "") + System.currentTimeMillis() + suffix;
// 对象键(Key)是对象在存储桶中的唯一标识。
key = StringUtils.isBlank(StringUtils.trim(rootPath)) ? fileName : rootPath + "/" + fileName;
minioClient.putObject(PutObjectArgs.builder()
.bucket(minioProperties.getBucketName())
.object(key)
.stream(inputStream, inputStream.available(), 5 * 1024 * 1024).build());
} catch (Exception e) {
e.printStackTrace();
throw new CustomizeFileException(ReturnCode.FILE_UPLOAD_EXCEPTION);
} finally {
IOUtils.closeQuietly(inputStream);
}
return (minioProperties.getEnableTls() ? Constantes.HTTPS : Constantes.HTTP)
+ minioProperties.getEndpoint() + "/" + minioProperties.getBucketName() + "/" + key;
}
/**
* 从MinIO中删除文件
*
* @param url 文件URL
*/
public boolean deleteInMinio(String url) {
MinioClient minioClient = getMinioClient();
String[] split = url.split(minioProperties.getEndpoint() + "/" + minioProperties.getBucketName() + "/");
if (split.length != 2) {
throw new CustomizeReturnException(ReturnCode.USER_FILE_ADDRESS_IS_ABNORMAL);
}
String key = split[1];
try {
minioClient.removeObject(RemoveObjectArgs.builder()
.bucket(minioProperties.getBucketName())
.object(key).build());
} catch (Exception e) {
throw new CustomizeFileException(ReturnCode.USER_FILE_DELETION_IS_ABNORMAL);
}
return true;
}
/**
* 获取MinioClient客户端
*
* @return 返回MinioClient客户端
*/
private MinioClient getMinioClient() {
try {
String[] ipAndPort = minioProperties.getEndpoint().split(":");
return MinioClient.builder()
.endpoint(ipAndPort[0], Integer.parseInt(ipAndPort[1]), minioProperties.getEnableTls())
.credentials(minioProperties.getRootUser(), minioProperties.getRootPassword())
.build();
} catch (Exception e) {
log.error("MinIO服务器构建异常:{}", e.getMessage());
throw new CustomizeFileException(ReturnCode.FILE_UPLOAD_EXCEPTION);
}
}
/**
* 依赖注入日志输出
*/
@PostConstruct
private void initDi() {
log.info("############ {} Configuration DI.", this.getClass().getSimpleName());
}
}
3. 编写Minio工具类
MinioUtils
/**
* MinIO工具类
*
* @author Ccoo
*/
@Slf4j
public class MinioUtils {
/**
* 被封装的MinIO对象
*/
private static final MinioConfiguration MINIO_CONFIGURATION = SpringContextHolder.getBean(MinioConfiguration.class);
/**
* 上传文件
*
* @param file 上传的文件数据
* @param rootPath 文件根目录(注意不需要首尾斜杠,即如果保存文件到"/root/a/"文件夹中,只需要传入"root/a"字符串即可)
* @return 文件所在路径
*/
public static String upload(MultipartFile file, String rootPath) {
return MINIO_CONFIGURATION.uploadToMinio(file, rootPath);
}
/**
* 上传文件
*
* @param inputStream 待上传的文件流
* @param suffix 文件后缀
* @param rootPath 上传的路径
* @return 文件所在路径
*/
public static String upload(InputStream inputStream, String suffix, String rootPath) {
return MINIO_CONFIGURATION.uploadToMinio(inputStream, suffix, rootPath);
}
/**
* 上传文件
*
* @param bytes 待上传的文件字节数据
* @param suffix 文件后缀
* @param rootPath 上传的路径
* @return 文件所在路径
*/
public static String upload(byte[] bytes, String suffix, String rootPath) {
return MINIO_CONFIGURATION.uploadToMinio(bytes, suffix, rootPath);
}
/**
* 删除文件
*
* @param url 文件所在地址
*/
public static boolean delete(String url) {
return MINIO_CONFIGURATION.deleteInMinio(url);
}
}
4. 编写Controller
MinioController
/**
* @author Ccoo
* 2024/2/20
*/
@Api(tags = "文件相关接口")
@Slf4j
@RestController
@RequestMapping(value = "/system/minio")
public class MinioController {
@ApiOperation(value = "文件上传返回url")
@PostMapping("/upload")
public R<String> upload(@RequestParam(value = "file") MultipartFile file, String rootPath) {
String objectName = MinioUtils.upload(file, rootPath);
if (null != objectName) {
return Re.ok(objectName);
}
return Re.fail("上传失败");
}
@ApiOperation(value = "删除文件", notes = "根据url地址删除文件")
@PostMapping("/delete")
public R<String> remove(String url) {
boolean result = MinioUtils.delete(url);
if (result) {
return Re.ok("删除成功");
}
return Re.fail("删除失败");
}
}