当前位置: 首页 > article >正文

SpringBoot整合Minio及阿里云OSS(配置文件无缝切换)

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_USERMINIO_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: minio
  minio:
    endpoint: http://192.168.1.102:9000
    accessKey: root
    secretKey: root
    bucketImageName: test

  #阿里云对象存储的配置信息
  aliyun:
    accessKey: xxxxx
    accessSecret: xxxxx
    endpoint: oss-cn-hangzhou.aliyuncs.com
    bucketImageName: 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 {

    @Resource
    private MinioOSSProperties ossProperties;

    @Bean
    @SneakyThrows
    public MinioClient minioClient() {
        return MinioClient.builder()
                .endpoint(ossProperties.getEndpoint())
                .credentials(ossProperties.getAccessKey(), ossProperties.getSecretKey())
                .build();
    }

}
3.操作接口实现
/**
 * minio操作工具类
 * @author moshangshang
 */
@Slf4j
@Data
@Component
public class MinioUtils {

    @Resource
    private MinioClient minioClient;

    @Resource
    private 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 {

    @Resource
    private AliYunOSSProperties ossProperties;

    @Bean
    @SneakyThrows
    public 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 {

    @Resource
    private OSS ossClient;

    @Resource
    private AliYunOSSProperties aliYunOSSProperties;


    @Override
    public 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 {

    @Resource
    private 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();
    }


}

http://www.kler.cn/news/293791.html

相关文章:

  • MySQL · 性能优化 · 提高查询效率的实用指南(下)
  • 用Python导入CSV和Excel表格数据到Word表格
  • 启动 Spring Boot 项目时指定特定的 application.yml 文件位置
  • 无人机种类详解!!!
  • DPDK基础入门(四):从源码角度解析同步互斥机制
  • 乐凡三防|国产化浪潮下的三防平板
  • 在VMware虚拟机中编译文件的时候报错:找不到头文件ft2build.h
  • 【2024高教社杯全国大学生数学建模竞赛】ABCDEF题 问题分析、模型建立、参考文献及实现代码
  • (一)十分简易快速 自己训练样本 opencv级联haar分类器 车牌识别
  • (pycharm)安装python库函数Matplotlib步骤
  • 备份还原 本地所有的Docker 镜像并且在另一台机器上还原
  • 【LeetCode 121】买卖股票的最佳时机
  • 【深入理解SpringCloud微服务】深入理解nacos配置中心(三)——服务端启动与获取配置源码分析
  • UNI-APP 溢出隐藏显示省略号
  • Hive SQL 分组与连接操作详解
  • html css网页制作成品
  • java计算机毕设课设—企业员工信息管理系统(附源码、文章、相关截图、部署视频)
  • 【STM32开发】GPIO最全解析及应用实例
  • Linux磁盘管理(精要)
  • 【数据结构-二维前缀和】力扣1277. 统计全为 1 的正方形子矩阵
  • SQL的高级查询练习知识点(day24)
  • centos8stream 修改为阿里云yum源
  • SQL进阶技巧:如何取时间序列最新完成状态的前一个状态并将完成状态的过程进行合并?
  • DataX用hdfsreader导入或导出hive数据
  • EmguCV学习笔记 C# 第10章 人脸识别
  • BMP280气压传感器详解(STM32)
  • Github优秀开源项目推荐
  • react antd table expandable defaultExpandAllRows 不生效问题
  • 知识付费最新版知识付费做的最好的平台,网创资源知识付费 知识付费网站搭建,搭建知识付费APP平台教学:在线教育系统源码。
  • NGINX 中配置负载均衡器