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

本文主要是介绍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: 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();}}

这篇关于SpringBoot整合Minio及阿里云OSS(配置文件无缝切换)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1144605

相关文章

JVM 的类初始化机制

前言 当你在 Java 程序中new对象时,有没有考虑过 JVM 是如何把静态的字节码(byte code)转化为运行时对象的呢,这个问题看似简单,但清楚的同学相信也不会太多,这篇文章首先介绍 JVM 类初始化的机制,然后给出几个易出错的实例来分析,帮助大家更好理解这个知识点。 JVM 将字节码转化为运行时对象分为三个阶段,分别是:loading 、Linking、initialization

Spring Security 基于表达式的权限控制

前言 spring security 3.0已经可以使用spring el表达式来控制授权,允许在表达式中使用复杂的布尔逻辑来控制访问的权限。 常见的表达式 Spring Security可用表达式对象的基类是SecurityExpressionRoot。 表达式描述hasRole([role])用户拥有制定的角色时返回true (Spring security默认会带有ROLE_前缀),去

浅析Spring Security认证过程

类图 为了方便理解Spring Security认证流程,特意画了如下的类图,包含相关的核心认证类 概述 核心验证器 AuthenticationManager 该对象提供了认证方法的入口,接收一个Authentiaton对象作为参数; public interface AuthenticationManager {Authentication authenticate(Authenti

Spring Security--Architecture Overview

1 核心组件 这一节主要介绍一些在Spring Security中常见且核心的Java类,它们之间的依赖,构建起了整个框架。想要理解整个架构,最起码得对这些类眼熟。 1.1 SecurityContextHolder SecurityContextHolder用于存储安全上下文(security context)的信息。当前操作的用户是谁,该用户是否已经被认证,他拥有哪些角色权限…这些都被保

Spring Security基于数据库验证流程详解

Spring Security 校验流程图 相关解释说明(认真看哦) AbstractAuthenticationProcessingFilter 抽象类 /*** 调用 #requiresAuthentication(HttpServletRequest, HttpServletResponse) 决定是否需要进行验证操作。* 如果需要验证,则会调用 #attemptAuthentica

Spring Security 从入门到进阶系列教程

Spring Security 入门系列 《保护 Web 应用的安全》 《Spring-Security-入门(一):登录与退出》 《Spring-Security-入门(二):基于数据库验证》 《Spring-Security-入门(三):密码加密》 《Spring-Security-入门(四):自定义-Filter》 《Spring-Security-入门(五):在 Sprin

Java架构师知识体认识

源码分析 常用设计模式 Proxy代理模式Factory工厂模式Singleton单例模式Delegate委派模式Strategy策略模式Prototype原型模式Template模板模式 Spring5 beans 接口实例化代理Bean操作 Context Ioc容器设计原理及高级特性Aop设计原理Factorybean与Beanfactory Transaction 声明式事物

Java进阶13讲__第12讲_1/2

多线程、线程池 1.  线程概念 1.1  什么是线程 1.2  线程的好处 2.   创建线程的三种方式 注意事项 2.1  继承Thread类 2.1.1 认识  2.1.2  编码实现  package cn.hdc.oop10.Thread;import org.slf4j.Logger;import org.slf4j.LoggerFactory

JAVA智听未来一站式有声阅读平台听书系统小程序源码

智听未来,一站式有声阅读平台听书系统 🌟&nbsp;开篇:遇见未来,从“智听”开始 在这个快节奏的时代,你是否渴望在忙碌的间隙,找到一片属于自己的宁静角落?是否梦想着能随时随地,沉浸在知识的海洋,或是故事的奇幻世界里?今天,就让我带你一起探索“智听未来”——这一站式有声阅读平台听书系统,它正悄悄改变着我们的阅读方式,让未来触手可及! 📚&nbsp;第一站:海量资源,应有尽有 走进“智听

阿里开源语音识别SenseVoiceWindows环境部署

SenseVoice介绍 SenseVoice 专注于高精度多语言语音识别、情感辨识和音频事件检测多语言识别: 采用超过 40 万小时数据训练,支持超过 50 种语言,识别效果上优于 Whisper 模型。富文本识别:具备优秀的情感识别,能够在测试数据上达到和超过目前最佳情感识别模型的效果。支持声音事件检测能力,支持音乐、掌声、笑声、哭声、咳嗽、喷嚏等多种常见人机交互事件进行检测。高效推