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

[黑马头条]-项目整合对象存储服务MinIO

目录

MinIO简介

MinIO特点

开箱使用

安装启动

管理控制台

快速入门

创建工程,导入pom依赖

引导类

创建测试类,上传html文件

封装MinIO为starter

创建模块heima-file-starter

导入依赖

配置类

MinIOConfigProperties

MinIOConfig

封装操作minIO类

FileStorageService

MinIOFileStorageService

对外加入自动配置

其他微服务使用


MinIO简介

MinIO基于Apache License v2.0开源协议的对象存储服务,可以做为云存储的解决方案用来保存海量的图片,视频,文档。由于采用Golang实现,服务端可以工作在Windows,Linux, OS X和FreeBSD上。配置简单,基本是复制可执行程序,单行命令可以运行起来。MinIO兼容亚马逊S3云存储服务接口,非常适合于存储大容量非结构化的数据,例如图片、视频、日志文件、备份数据和容器/虚拟机镜像等,而一个对象文件可以是任意大小,从几kb到最大5T不等。

S3 ( Simple Storage Service简单存储服务)

基本概念

  • bucket – 类比于文件系统的目录

  • Object – 类比文件系统的文件

  • Keys – 类比文件名

官网文档:MinIO对象存储 Kubernetes — MinIO中文文档 | MinIO Kubernetes中文文档http://docs.minio.org.cn/docs/

MinIO特点

  • 数据保护

    Minio使用Minio Erasure Code(纠删码)来防止硬件故障。即便损坏一半以上的driver,但是仍然可以从中恢复。

  • 高性能

    作为高性能对象存储,在标准硬件条件下它能达到55GB/s的读、35GB/s的写速率

  • 可扩容

    不同MinIO集群可以组成联邦,并形成一个全局的命名空间,并跨越多个数据中心

  • SDK支持

    基于Minio轻量的特点,它得到类似Java、Python或Go等语言的sdk支持

  • 有操作页面

    面向用户友好的简单操作界面,非常方便的管理Bucket及里面的文件资源

  • 功能简单

    这一设计原则让MinIO不容易出错、更快启动

  • 丰富的API

    支持文件资源的分享连接及分享链接的过期策略、存储桶操作、文件列表访问及文件上传下载的基本功能等。

  • 文件变化主动通知

    存储桶(Bucket)如果发生改变,比如上传对象和删除对象,可以使用存储桶事件通知机制进行监控,并通过以下方式发布出去:AMQP、MQTT、Elasticsearch、Redis、NATS、MySQL、Kafka、Webhooks等。

开箱使用

安装启动

我们提供的镜像中已经有minio的环境,或者自行拉取镜像也行

我们可以使用docker进行环境部署和启动

docker run -p 9000:9000 --name minio -d --restart=always -e "MINIO_ACCESS_KEY=minio" -e "MINIO_SECRET_KEY=minio123" -v /home/data:/data -v /home/config:/root/.minio minio/minio server /data

关于该代码的解释如下:

管理控制台

假设我们的服务器地址为http://192.168.200.130:9000,我们在地址栏输入:http://http://192.168.200.130:9000/ 即可进入登录界面。

这里的ip地址需要是你自己虚拟机上的地址,或者是本地地址,这个取决于你的MinIO在哪

Access Key为minio   Secret_key 为minio123    进入系统后可以看到主界面

账号和密码是我们创建容器时设定的,输入你自己设定的账号密码即可

点击右下角的“+”号 ,点击下面的图标,创建一个桶

 至此,我们的MinIO环境搭载好了,接下来就是和项目整合了

快速入门

创建工程,导入pom依赖

创建minio-demo,对应pom如下

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><parent><artifactId>heima-leadnews-test</artifactId><groupId>com.heima</groupId><version>1.0-SNAPSHOT</version></parent><modelVersion>4.0.0</modelVersion><artifactId>minio-demo</artifactId><properties><maven.compiler.source>8</maven.compiler.source><maven.compiler.target>8</maven.compiler.target></properties><dependencies><dependency><groupId>io.minio</groupId><artifactId>minio</artifactId><version>7.1.0</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId></dependency></dependencies></project>

引导类

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
public class MinIOApplication {public static void main(String[] args) {SpringApplication.run(MinIOApplication.class,args);}
}

创建测试类,上传html文件

import io.minio.MinioClient;
import io.minio.PutObjectArgs;import java.io.FileInputStream;public class MinIOTest {public static void main(String[] args) {FileInputStream fileInputStream = null;try {fileInputStream =  new FileInputStream("D:\\list.html");;//1.创建minio链接客户端MinioClient minioClient = MinioClient.builder().credentials("minio", "minio123").endpoint("http://192.168.200.130:9000").build();//2.上传PutObjectArgs putObjectArgs = PutObjectArgs.builder().object("list.html")//文件名.contentType("text/html")//文件类型.bucket("leadnews")//桶名词  与minio创建的名词一致.stream(fileInputStream, fileInputStream.available(), -1) //文件流.build();minioClient.putObject(putObjectArgs);System.out.println("http://192.168.200.130:9000/leadnews/ak47.jpg");} catch (Exception ex) {ex.printStackTrace();}}}

项目的结构图如下所示:

封装MinIO为starter

在我们项目的开发过程中,为了更好的便于我们开发,我们一般会将MinIO为starter或者是工具类,这样在项目开发的时候,就可以直接调用方法就可以使得项目整合MinIO功能。

创建模块heima-file-starter

导入依赖

<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-autoconfigure</artifactId></dependency><dependency><groupId>io.minio</groupId><artifactId>minio</artifactId><version>7.1.0</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-configuration-processor</artifactId><optional>true</optional></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-actuator</artifactId></dependency>
</dependencies>

这段代码列出了一个Java项目的依赖项,包括用于Spring Boot自动配置、核心功能、配置处理和Actuator监控的库,以及用于对象存储操作的Minio客户端库。 

配置类

MinIOConfigProperties
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;import java.io.Serializable;@Data
@ConfigurationProperties(prefix = "minio")  // 文件上传 配置前缀file.oss
public class MinIOConfigProperties implements Serializable {private String accessKey;private String secretKey;private String bucket;private String endpoint;private String readPath;
}

这段代码定义了一个名为 MinIOConfigProperties 的Java类,该类使用了Lombok的 @Data 注解来自动生成getter和setter方法,并实现了 Serializable 接口以便序列化。通过 @ConfigurationProperties(prefix = "minio") 注解,它与Spring Boot配置文件中的 minio 前缀属性进行绑定,用于存储MinIO对象存储服务的相关配置信息,包括访问密钥( accessKey )、秘密密钥( secretKey )、存储桶名称( bucket )、服务端点地址( endpoint )和读取路径( readPath )等属性。

MinIOConfig
import com.heima.file.service.FileStorageService;
import io.minio.MinioClient;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;@Data
@Configuration
@EnableConfigurationProperties({MinIOConfigProperties.class})
//当引入FileStorageService接口时
@ConditionalOnClass(FileStorageService.class)
public class MinIOConfig {@Autowiredprivate MinIOConfigProperties minIOConfigProperties;@Beanpublic MinioClient buildMinioClient(){return MinioClient.builder().credentials(minIOConfigProperties.getAccessKey(), minIOConfigProperties.getSecretKey()).endpoint(minIOConfigProperties.getEndpoint()).build();}
}

这段代码是一个Spring Boot配置类,用于配置MinIO客户端连接。 @Configuration 注解表明这是一个配置类, @EnableConfigurationProperties 注解启用了 MinIOConfigProperties 类中的配置属性,允许从配置文件加载与 minio 前缀相关的属性值。 @ConditionalOnClass 注解表示当 FileStorageService 类存在于类路径时,该配置类才生效。类中注入了 MinIOConfigProperties 对象,以获取配置文件中的MinIO连接信息。 @Bean 方法 buildMinioClient 使用这些配置信息构建并返回一个 MinioClient 实例,用于与MinIO服务器进行交互。

封装操作minIO类

FileStorageService
import java.io.InputStream;/*** @author itheima*/
public interface FileStorageService {/***  上传图片文件* @param prefix  文件前缀* @param filename  文件名* @param inputStream 文件流* @return  文件全路径*/public String uploadImgFile(String prefix, String filename,InputStream inputStream);/***  上传html文件* @param prefix  文件前缀* @param filename   文件名* @param inputStream  文件流* @return  文件全路径*/public String uploadHtmlFile(String prefix, String filename,InputStream inputStream);/*** 删除文件* @param pathUrl  文件全路径*/public void delete(String pathUrl);/*** 下载文件* @param pathUrl  文件全路径* @return**/public byte[]  downLoadFile(String pathUrl);}

这段代码定义了一个 FileStorageService 接口,用于处理文件存储操作。接口中声明了四个方法: uploadImgFile 用于上传图片文件, uploadHtmlFile 用于上传HTML文件,这两个方法都接受文件前缀、文件名和文件流作为参数,并返回文件的全路径; delete 方法用于根据文件全路径删除文件; downLoadFile 方法用于根据文件全路径下载文件并返回文件的字节数组。

MinIOFileStorageService
import com.heima.file.config.MinIOConfig;
import com.heima.file.config.MinIOConfigProperties;
import com.heima.file.service.FileStorageService;
import io.minio.GetObjectArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.RemoveObjectArgs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Import;
import org.springframework.util.StringUtils;import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;@Slf4j
@EnableConfigurationProperties(MinIOConfigProperties.class)
@Import(MinIOConfig.class)
public class MinIOFileStorageService implements FileStorageService {@Autowiredprivate MinioClient minioClient;@Autowiredprivate MinIOConfigProperties minIOConfigProperties;private final static String separator = "/";/*** @param dirPath* @param filename  yyyy/mm/dd/file.jpg* @return*/public String builderFilePath(String dirPath,String filename) {StringBuilder stringBuilder = new StringBuilder(50);if(!StringUtils.isEmpty(dirPath)){stringBuilder.append(dirPath).append(separator);}SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");String todayStr = sdf.format(new Date());stringBuilder.append(todayStr).append(separator);stringBuilder.append(filename);return stringBuilder.toString();}/***  上传图片文件* @param prefix  文件前缀* @param filename  文件名* @param inputStream 文件流* @return  文件全路径*/@Overridepublic String uploadImgFile(String prefix, String filename,InputStream inputStream) {String filePath = builderFilePath(prefix, filename);try {PutObjectArgs putObjectArgs = PutObjectArgs.builder().object(filePath).contentType("image/jpg").bucket(minIOConfigProperties.getBucket()).stream(inputStream,inputStream.available(),-1).build();minioClient.putObject(putObjectArgs);StringBuilder urlPath = new StringBuilder(minIOConfigProperties.getReadPath());urlPath.append(separator+minIOConfigProperties.getBucket());urlPath.append(separator);urlPath.append(filePath);return urlPath.toString();}catch (Exception ex){log.error("minio put file error.",ex);throw new RuntimeException("上传文件失败");}}/***  上传html文件* @param prefix  文件前缀* @param filename   文件名* @param inputStream  文件流* @return  文件全路径*/@Overridepublic String uploadHtmlFile(String prefix, String filename,InputStream inputStream) {String filePath = builderFilePath(prefix, filename);try {PutObjectArgs putObjectArgs = PutObjectArgs.builder().object(filePath).contentType("text/html").bucket(minIOConfigProperties.getBucket()).stream(inputStream,inputStream.available(),-1).build();minioClient.putObject(putObjectArgs);StringBuilder urlPath = new StringBuilder(minIOConfigProperties.getReadPath());urlPath.append(separator+minIOConfigProperties.getBucket());urlPath.append(separator);urlPath.append(filePath);return urlPath.toString();}catch (Exception ex){log.error("minio put file error.",ex);ex.printStackTrace();throw new RuntimeException("上传文件失败");}}/*** 删除文件* @param pathUrl  文件全路径*/@Overridepublic void delete(String pathUrl) {String key = pathUrl.replace(minIOConfigProperties.getEndpoint()+"/","");int index = key.indexOf(separator);String bucket = key.substring(0,index);String filePath = key.substring(index+1);// 删除ObjectsRemoveObjectArgs removeObjectArgs = RemoveObjectArgs.builder().bucket(bucket).object(filePath).build();try {minioClient.removeObject(removeObjectArgs);} catch (Exception e) {log.error("minio remove file error.  pathUrl:{}",pathUrl);e.printStackTrace();}}/*** 下载文件* @param pathUrl  文件全路径* @return  文件流**/@Overridepublic byte[] downLoadFile(String pathUrl)  {String key = pathUrl.replace(minIOConfigProperties.getEndpoint()+"/","");int index = key.indexOf(separator);String bucket = key.substring(0,index);String filePath = key.substring(index+1);InputStream inputStream = null;try {inputStream = minioClient.getObject(GetObjectArgs.builder().bucket(minIOConfigProperties.getBucket()).object(filePath).build());} catch (Exception e) {log.error("minio down file error.  pathUrl:{}",pathUrl);e.printStackTrace();}ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();byte[] buff = new byte[100];int rc = 0;while (true) {try {if (!((rc = inputStream.read(buff, 0, 100)) > 0)) break;} catch (IOException e) {e.printStackTrace();}byteArrayOutputStream.write(buff, 0, rc);}return byteArrayOutputStream.toByteArray();}
}

这段代码是一个实现文件存储服务的类 MinIOFileStorageService ,它实现了 FileStorageService 接口,使用MinIO作为对象存储解决方案。通过 @Slf4j 注解引入日志功能, @EnableConfigurationProperties 和 @Import 注解用于加载配置属性和导入配置类。类中包含上传图片和HTML文件、删除文件、下载文件的方法,利用MinIO客户端进行文件操作,并处理文件路径构建和异常。这个实现类提供了完整的文件存储服务,适用于需要与MinIO对象存储交互的场景。 

对外加入自动配置

因为MinIO在独立的子微服务里,如果其他微服务需要使用的话,其他微服务必须扫描到这个微服务,在这里我们将微服务做自动配置,这样项目启动后,会被加载为被spring管理的bean对象,其他微服务就可以获取到该对象提供的服务。
在resources中新建`META-INF/spring.factories`

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\com.heima.file.service.impl.MinIOFileStorageService

这行配置出现在Spring Boot项目的配置文件中,如`application.properties`或`application.yml`,其目的是启用Spring Boot的自动配置机制,以便自动配置`com.heima.file.service.impl.MinIOFileStorageService`类。通过指定这个类,Spring Boot会扫描并注册该类为Spring容器中的一个Bean,从而使得该类的依赖注入和其他由Spring管理的行为生效。

`MinIOFileStorageService`类很可能是一个服务实现类,它提供了与MinIO对象存储服务交互的功能,如文件上传、下载和删除等。通过这种自动配置方式,开发者无需手动声明该类的Bean,简化了配置过程并减少了出错的可能性。

此外,这种配置方式也表明`MinIOFileStorageService`类可能使用了Spring的注解(如`@Service`、`@Autowired`等)来实现依赖注入和其他Spring特性。因此,这个配置项是将该类集成到Spring Boot应用中的关键步骤,确保其能够正常工作并与其他Spring管理的组件协同。

我们项目的结构如下所示:

其他微服务使用

第一,导入heima-file-starter的依赖,即我们刚刚自定义的MinIO微服务的依赖;

第二,在微服务中添加minio所需要的配置

minio:accessKey: miniosecretKey: minio123bucket: leadnewsendpoint: http://192.168.200.130:9000readPath: http://192.168.200.130:9000

根据你自己的情况进行调整

第三,在对应使用的业务类中注入FileStorageService,样例如下:

import com.heima.file.service.FileStorageService;
import com.heima.minio.MinioApplication;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;import java.io.FileInputStream;
import java.io.FileNotFoundException;@SpringBootTest(classes = MinioApplication.class)
@RunWith(SpringRunner.class)
public class MinioTest {@Autowiredprivate FileStorageService fileStorageService;@Testpublic void testUpdateImgFile() {try {FileInputStream fileInputStream = new FileInputStream("E:\\tmp\\ak47.jpg");String filePath = fileStorageService.uploadImgFile("", "ak47.jpg", fileInputStream);System.out.println(filePath);} catch (FileNotFoundException e) {e.printStackTrace();}}
}

 至此,在项目中整合MinIO服务成功,就可以快捷开发啦!

http://www.dtcms.com/a/287103.html

相关文章:

  • 百度网盘TV版1.21.0 |支持倍速播放,大屏云看片
  • CS231n-2017 Lecture2图像分类笔记
  • 工业企业与污染库匹配数据库(1998-2014年)
  • Letter Combination of a Phone Number
  • Redis原理之集群
  • windows内核研究(驱动开发之内核编程)
  • Qt控件实战详解:深入掌握输入输出与数据展示
  • Python MCP与Excel增强智能:构建下一代数据处理和自动化解决方案
  • SpringBoot 3.0 挥别 spring.factories,拥抱云原生新纪元
  • 人该怎样活着呢?55
  • 【RK3576】Android 14 驱动开发实战指南
  • uview-ui使用u-icon文字图标展示
  • 报错:升级gcc,centos
  • 数据库第五次作业
  • 云边端协同架构下的智能计算革命
  • 从代码学习深度强化学习 - SAC PyTorch版
  • 消息队列与信号量:System V 进程间通信的基础
  • 【机器学习深度学习】为什么要将模型转换为 GGUF 格式?
  • win10连接鼠标自动关闭触摸板/win10关闭触摸板(笔记本)
  • 路由器的Serial 串口理解
  • 移除debian升级后没用的垃圾
  • 爬虫逆向之JS混淆案例(全国招标公告公示搜索引擎 type__1017逆向)
  • AJAX概述
  • Unity 3D碰撞器
  • C语言—深入理解指针(详)
  • Eureka 和 Nacos
  • 医疗AI与融合数据库的整合:挑战、架构与未来展望(下)
  • Acrobat SDK 核心架构、应用
  • 2025年最新秋招java后端面试八股文+场景题
  • Linux操作系统之线程(三)