SpringBoot整合Minio及阿里云OSS
文章目录
- SpringBoot整合Minio及阿里云OSS
- 1.Minio安装测试
- 1.Docker安装
- 启动容器
- 2.创建bucket
- 3.上传文件
- 修改权限
- 2.SpringBoot整合Minio及阿里云OSS
- 1.公共部分抽取
- 2.Minio配置整合
- 1.添加pom依赖
- 2.添加配置文件
- 3.操作接口实现
- 3.阿里云OSS配置整合
- 1.pom依赖
- 2.添加配置文件
- 3.操作接口实现
- 4.测试
1.Minio安装测试
MinIO是一个对象存储解决方案,它提供了与Amazon Web Services S3兼容的API,并支持所有核心S3功能。 MinIO有能力在任何地方部署 - 公有云或私有云,裸金属基础设施,编排环境,以及边缘基础设施。
文档地址:https://www.minio.org.cn/docs/minio/linux/developers/java/API.html#
1.Docker安装
拉取对应的镜像
docker pull minio/minio
创建挂载目录
mkdir -p /dockerData/minio/data
mkdir -p /dockerData/minio/config
启动容器
然后我们启动我们的容器,后面有个目录,就是我们需要挂载的硬盘目录
docker run --privileged -it -p 9000:9000 --name minio \
-e "MINIO_ACCESS_KEY=moshangshang2024" \
--privileged=true \
-e "MINIO_SECRET_KEY=moshangshang2024" \
-v /dockerData/minio/data:/data \
-v /dockerData/minio/config:/root/.minio \
minio/minio server /data
最新版本的minio启动使用这条语句
其中修改了MINIO_ROOT_USER
和MINIO_ROOT_PASSWORD
名称,增加了web控制台端口,密码长度需大于8位
docker run --privileged -it \
--name minio \
-p 9000:9000 \
-p 9090:9090 \
-d --restart=always \
-e "MINIO_ROOT_USER=moshangshang2024" \
-e "MINIO_ROOT_PASSWORD=xxxxxxxx" \
-v /dockerData/minio/data:/data \
-v /dockerData/minio/config:/root/.minio \
minio/minio server /data --console-address ":9090" --address ":9000"
我们只需要访问上面提到的ip地址
http://192.168.1.101:9000
输入刚刚配置的账号moshangshang2024和密码 即可进入
2.创建bucket
我们首先需要创建一个桶,可以当成是一个目录,选择 create bucket进行创建
3.上传文件
然后我们选中我们的桶,选择 upload 进行文件上传
修改权限
如果要使用SDK,比如Java客户端来操作我们的minio的话,那么我们还需要修改一下我们的bucket权限
然后就可以通过http://ip:9000/存储桶名/文件名访问文件
2.SpringBoot整合Minio及阿里云OSS
1.公共部分抽取
1.添加自定义yml配置
#对象存储
oss:#对象存储切换配置type: miniominio:endpoint: http://192.168.1.102:9000accessKey: rootsecretKey: rootbucketImageName: test#阿里云对象存储的配置信息aliyun:accessKey: xxxxxaccessSecret: xxxxxendpoint: oss-cn-hangzhou.aliyuncs.combucketImageName: test
2.公共操作方法接口
package com.li.test.minio;import org.springframework.web.multipart.MultipartFile;import javax.servlet.http.HttpServletResponse;
import java.util.List;public interface OSSOperation {/*** 获取默认bucketName** @return 返回 名称*/public String getBucketName();/*** 校验bucket是否存在** @param bucketName 桶名称* @return 返回 boolean - 如果存储桶存在,则为 True。*/public boolean checkBucketExist(String bucketName);/*** 列出所有存储桶的存储桶信息*/public List<String> listBuckets();/*** 创建一个存储桶** @param bucketName 桶名称* @return 返回 boolean - 如果执行成功,则为 True。*/public boolean makeBucket(String bucketName);/*** 删除一个空的存储桶** @param bucketName 桶名称* @return 返回 boolean - 如果执行成功,则为 True。*/public boolean removeBucket(String bucketName);/*** 文件上传** @param data 文件数据* @param bucketName 上传的桶名称*/public boolean uploadFile(MultipartFile data, String bucketName);/*** 文件上传** @param fileName 文件名* @param bucketName 上传的桶名称*/public void downloadFile( String fileName, String bucketName, HttpServletResponse response);/*** 文件删除** @param fileName 文件名* @param bucketName 上传的桶名称*/public boolean removeFile(String fileName, String bucketName);
}
2.Minio配置整合
1.添加pom依赖
<dependency><groupId>io.minio</groupId><artifactId>minio</artifactId><version>8.5.10</version></dependency>
2.添加配置文件
然后我们需要编写配置文件,用于初始化配置 MinioClient装载到spring容器中
@Data
@ConfigurationProperties(prefix = "oss.minio")
public class MinioOSSProperties {private String endpoint;private String accessKey;private String secretKey;private String bucketImageName;}
/*** Minio配置类** @author moshangshang*/
@Configuration
@EnableConfigurationProperties(MinioOSSProperties.class)
@ConditionalOnProperty(prefix = "oss", name = "type",havingValue = "minio", matchIfMissing = true)
public class MinioOSSConfiguration {@Resourceprivate MinioOSSProperties ossProperties;@Bean@SneakyThrowspublic MinioClient minioClient() {return MinioClient.builder().endpoint(ossProperties.getEndpoint()).credentials(ossProperties.getAccessKey(), ossProperties.getSecretKey()).build();}}
3.操作接口实现
/*** minio操作工具类* @author moshangshang*/
@Slf4j
@Data
@Component
public class MinioUtils {@Resourceprivate MinioClient minioClient;@Resourceprivate OssMinioProperties minioProperties;/*** 校验bucket是否存在** @param bucketName 桶名称* @return 返回 boolean - 如果存储桶存在,则为 True。*/public boolean checkBucketExist(String bucketName) {boolean found = false;try {found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());if (found) {log.info("{} exists", bucketName);} else {log.info("{} not exist", bucketName);}} catch (Exception e) {log.info("{} checkBucketExist exception", bucketName,e);}return found;}/*** 列出所有存储桶的存储桶信息*/public List<Bucket> listBuckets() {List<Bucket> buckets = new ArrayList<>();try {buckets = minioClient.listBuckets();} catch (Exception e) {log.info("listBuckets exception......",e);}return buckets;}/*** 创建一个存储桶** @param bucketName 桶名称* @return 返回 boolean - 如果执行成功,则为 True。*/public boolean makeBucket(String bucketName) {boolean found = false;try {minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());found = true;} catch (Exception e) {log.info("{} makeBucket exception {}", bucketName,e.getMessage(),e);}return found;}/*** 删除一个空的存储桶** @param bucketName 桶名称* @return 返回 boolean - 如果执行成功,则为 True。*/public boolean removeBucket(String bucketName) {boolean found = false;try {minioClient.removeBucket(RemoveBucketArgs.builder().bucket(bucketName).build());found = true;} catch (Exception e) {log.info("{} removeBucket exception", bucketName);}return found;}/*** 文件上传** @param data 文件数据* @param bucketName 上传的桶名称*/public boolean uploadFile(MultipartFile data, String bucketName) {boolean flag = checkBucketExist(bucketName);if (!flag){return false;}String fileName = data.getOriginalFilename();InputStream is = null;try {is = data.getInputStream();minioClient.putObject(PutObjectArgs.builder().bucket(bucketName).object(fileName).stream(is, data.getSize(), -1).contentType(data.getContentType()).build());return true;} catch (Exception e) {log.info("{} upload exception", bucketName,e);}return false;}/*** 文件上传** @param fileName 文件名* @param bucketName 上传的桶名称*/public void downloadFile( String fileName, String bucketName, HttpServletResponse response) {GetObjectResponse is = null;try {GetObjectArgs getObjectArgs = GetObjectArgs.builder().bucket(bucketName).object(fileName).build();is = minioClient.getObject(getObjectArgs);response.setContentType("application/octet-stream");response.setCharacterEncoding("utf-8");response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "utf-8"));IoUtil.copy(is, response.getOutputStream());log.info("minio downloadFile success, filePath:{}", fileName);} catch (Exception e) {log.error("minio downloadFile Exception:{}", e.getMessage(), e);} finally {IoUtil.close(is);}}/*** 文件删除** @param fileName 文件名* @param bucketName 上传的桶名称*/public boolean removeFile(String fileName, String bucketName) {boolean flag = checkBucketExist(bucketName);if (!flag){return false;}try {minioClient.removeObject(RemoveObjectArgs.builder().bucket(bucketName).object(fileName).build());return true;} catch (Exception e) {log.error("minio removeFile Exception:{}", e.getMessage(), e);}return false;}
}
3.阿里云OSS配置整合
1.pom依赖
<dependency><groupId>com.aliyun.oss</groupId><artifactId>aliyun-sdk-oss</artifactId><version>3.10.2</version></dependency>
2.添加配置文件
@Data
@ConfigurationProperties(prefix = "oss.aliyun")
public class AliYunOSSProperties {private String accessKey;private String accessSecret;private String endpoint;private String bucketImageName;}
/*** 阿里云oss配置类** @author moshangshang*/
@Configuration
@EnableConfigurationProperties(AliYunOSSProperties.class)
@ConditionalOnProperty(prefix = "oss", name = "type",havingValue = "aliyun", matchIfMissing = true)
public class AliYunOSSConfiguration {@Resourceprivate AliYunOSSProperties ossProperties;@Bean@SneakyThrowspublic OSS ossClient() {return new OSSClientBuilder().build(ossProperties.getEndpoint(),ossProperties.getAccessKey(),ossProperties.getAccessSecret());}}
3.操作接口实现
/*** 阿里云oss操作工具类* @author moshangshang*/
@Slf4j
@Data
@Component
@ConditionalOnProperty(prefix = "oss", name = "type",havingValue = "aliyun", matchIfMissing = true)
public class AliYunOSSOperation implements OSSOperation {@Resourceprivate OSS ossClient;@Resourceprivate AliYunOSSProperties aliYunOSSProperties;@Overridepublic String getBucketName() {return aliYunOSSProperties.getBucketImageName();}/*** 校验bucket是否存在** @param bucketName 桶名称* @return 返回 boolean - 如果存储桶存在,则为 True。*/public boolean checkBucketExist(String bucketName) {boolean found = false;try {found = ossClient.doesBucketExist(bucketName);if (found) {log.info("{} exists", bucketName);} else {log.info("{} not exist", bucketName);}} catch (Exception e) {log.info("{} checkBucketExist exception", bucketName,e);}return found;}/*** 列出所有存储桶的存储桶信息*/public List<String> listBuckets() {List<String> result = new ArrayList<>();try {List<Bucket> buckets = ossClient.listBuckets();result = buckets.stream().map(Bucket::getName).collect(Collectors.toList());} catch (Exception e) {log.info("listBuckets exception......",e);}return result;}/*** 创建一个存储桶** @param bucketName 桶名称* @return 返回 boolean - 如果执行成功,则为 True。*/public boolean makeBucket(String bucketName) {boolean found = false;try {ossClient.createBucket(bucketName);found = true;} catch (Exception e) {log.info("{} makeBucket exception {}", bucketName,e.getMessage(),e);}return found;}/*** 删除一个空的存储桶** @param bucketName 桶名称* @return 返回 boolean - 如果执行成功,则为 True。*/public boolean removeBucket(String bucketName) {boolean found = false;try {ossClient.deleteBucket(bucketName);found = true;} catch (Exception e) {log.info("{} removeBucket exception", bucketName);}return found;}/*** 文件上传** @param data 文件数据* @param bucketName 上传的桶名称*/public boolean uploadFile(MultipartFile data, String bucketName) {String fileName = data.getOriginalFilename();InputStream is = null;try {is = data.getInputStream();ossClient.putObject(bucketName,fileName,data.getInputStream());return true;} catch (Exception e) {log.info("{} upload exception", bucketName,e);}return false;}/*** 文件下载** @param fileName 文件名* @param bucketName 上传的桶名称*/public void downloadFile( String fileName, String bucketName, HttpServletResponse response) {InputStream is = null;try {is = ossClient.getObject(bucketName,fileName).getObjectContent();response.setContentType("application/octet-stream");response.setCharacterEncoding("utf-8");response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "utf-8"));IoUtil.copy(is, response.getOutputStream());log.info("minio downloadFile success, filePath:{}", fileName);} catch (Exception e) {log.error("minio downloadFile Exception:{}", e.getMessage(), e);} finally {IoUtil.close(is);}}/*** 文件删除** @param fileName 文件名* @param bucketName 上传的桶名称*/public boolean removeFile(String fileName, String bucketName) {boolean flag = checkBucketExist(bucketName);if (!flag){return false;}try {ossClient.deleteObject(bucketName,fileName);return true;} catch (Exception e) {log.error("minio removeFile Exception:{}", e.getMessage(), e);}return false;}
}
4.测试
/*** minio测试* @author moshangshang*/
@Slf4j
@RestController
public class OSSController {@Resourceprivate OSSOperation ossOperation;@PostMapping("/check")public boolean checkBucketExist(@RequestParam("bucketName")String bucketName) {return ossOperation.checkBucketExist(bucketName);}@PostMapping("/upload")public boolean upload(@RequestParam("data") MultipartFile data) {return ossOperation.uploadFile(data, ossOperation.getBucketName());}@PostMapping("/download")public void download(@RequestParam("fileName")String fileName, HttpServletResponse response) {ossOperation.downloadFile(fileName, ossOperation.getBucketName(), response);}@PostMapping("/remove/file")public boolean removeFile(@RequestParam("fileName")String fileName) {return ossOperation.removeFile(fileName, ossOperation.getBucketName());}@PostMapping("/remove/bucket")public boolean removeBucket(@RequestParam("bucketName")String bucketName) {return ossOperation.removeBucket(bucketName);}@PostMapping("/add/bucket")public boolean makeBucket(@RequestParam("bucketName")String bucketName) {return ossOperation.makeBucket(bucketName);}@PostMapping("/bucket/list")public List<String> listBuckets() {return ossOperation.listBuckets();}}