【Java筆記】對象存儲服務MinIO

1 MinIO簡介

MinIO基于Apache License v2.0開源協議的對象存儲服務,可以做為云存儲的解決方案用來保存海量的圖片,視頻,文檔。由于采用Golang實現,服務端可以工作在Windows,Linux, OS X和FreeBSD上。配置簡單,基本是復制可執行程序,單行命令可以運行起來。

MinIO兼容亞馬遜S3云存儲服務接口,非常適合于存儲大容量非結構化的數據,例如圖片、視頻、日志文件、備份數據和容器/虛擬機鏡像等,而一個對象文件可以是任意大小,從幾kb到最大5T不等。

S3 ( Simple Storage Service簡單存儲服務)

基本概念

  • bucket – 類比于文件系統的目錄
  • Object – 類比文件系統的文件
  • Keys – 類比文件名

官網文檔:http://docs.minio.org.cn/docs/

2 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等。

3 開箱使用

3.3.1 安裝啟動

我們可以使用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

3.2 管理控制臺

假設我們的服務器地址為http://192.168.200.130:9000,我們在地址欄輸入:http://http://192.168.200.130:9000/即可進入登錄界面。
在這里插入圖片描述

Access Key為minio,Secret_key 為minio123(是在啟動docker中啟動minio容器時指定的賬號和密碼),進入系統后可以看到主界面

點擊右下角的“+”號 ,點擊下面的圖標,可以創建一個桶

4 快速入門

4.1 創建工程,導入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>

引導類:

package com.heima.minio;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);}
}

創建測試類MinIOTest ,上傳html文件

package com.heima.minio.test;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(fileI	nputStream, fileInputStream.available(), -1) //文件流.build();minioClient.putObject(putObjectArgs);System.out.println("http://192.168.200.130:9000/leadnews/ak47.jpg");} catch (Exception ex) {ex.printStackTrace();}}}

文件上傳后的訪問地址:http://192.168.200.130:9000/leadnews/list.html

如果上傳后不能訪問,需要在管理端修改權限,"edit policy" -> "read and write"
在這里插入圖片描述

5 整合Springboot

5.1 創建項目模塊 heima-file-starter

  1. 目錄結構
    在這里插入圖片描述

5.2 代碼實現

MinIOConfig.java配置類

package com.heima.file.config;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();}
}

MinIOConfigProperties.java 配置屬性

package com.heima.file.config;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;
}

工具類的接口FileStorageService .java

package com.heima.file.service;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);}

工具類具體實現 MinIOFileStorageService.java

package com.heima.file.service.impl;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();}
}

spring.factories 用于實現自動注配置(autoConfiguration,原理與spring自動配置相同)

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

5.3 其他模塊使用文件上傳服務

  1. 項目結構
    在這里插入圖片描述

  2. 引入依賴

    <dependencies><dependency><groupId>com.heima</groupId><artifactId>heima-file-starter</artifactId><version>1.0-SNAPSHOT</version></dependency></dependencies>
  1. 配置文件
minio:accessKey: miniosecretKey: minio123bucket: leadnewsendpoint: http://192.168.200.130:9000readPath: http://192.168.200.130:9000
  1. 啟動類
package minio;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);}
}
  1. 測試代碼
package minio;import com.heima.file.service.impl.MinIOFileStorageService;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
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 MinIOFileStorageService storageService;@Testpublic void testuploadImgFile(){FileInputStream fileInputStream = null;try {fileInputStream = new FileInputStream("D:\\testImg.jpg");String filePath = storageService.uploadImgFile("", "testImg.jpg", fileInputStream);System.out.println("filePath = " + filePath);} catch (FileNotFoundException e) {throw new RuntimeException(e);}}}
  1. 效果

文件訪問地址http://192.168.200.130:9000/leadnews/2023/08/14/testImg.jpg
在這里插入圖片描述
將根據上傳時的日期,生成目錄結構。

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/35899.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/35899.shtml
英文地址,請注明出處:http://en.pswp.cn/news/35899.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

mac-右鍵-用VSCode打開

1.點擊訪達&#xff0c;搜索自動操作 2.選擇快速操作 3.執行shell腳本 替換代碼如下&#xff1a; for f in "$" doopen -a "Visual Studio Code" "$f" donecommand s保存會出現一個彈框&#xff0c;保存為“用VSCode打開” 5.使用

基于百度語音識別API智能語音識別和字幕推薦系統——深度學習算法應用(含全部工程源碼)+測試數據集

目錄 前言總體設計系統整體結構圖系統流程圖 運行環境模塊實現1. 數據預處理2. 翻譯3. 格式轉換4. 音頻切割5. 語音識別6. 文本切割7. main函數 系統測試工程源代碼下載其它資料下載 前言 本項目基于百度語音識別API&#xff0c;結合了語音識別、視頻轉換音頻識別以及語句停頓…

【人工智能124種任務大集合】-集齊了自然語言處理(NLP),計算機視覺(CV),語音識別,多模態等任務

大家好&#xff0c;我是微學AI&#xff0c;今天給大家介紹一下人工智能124種任務大集合&#xff0c;任務集合主要包括4大類&#xff1a;自然語言處理&#xff08;NLP&#xff09;、計算機視覺&#xff08;CV&#xff09;、語音識別、多模態任務。 我這里整理了124種應用場景任…

JavaScript基礎之基于數據類型和引用數據類型

原文合集地址如下&#xff0c;有需要的朋友可以關注 本文地址 數據類型 JavaScript的數據類型有7中&#xff0c;包括6個基本類型和一個引用類型 基本數據類型&#xff1a;number, string, boolean, null, undefined, symbol 引用數據類型&#xff1a;object&#xff08;數組…

工業物聯網數據橋接教程:Modbus 橋接到 MQTT

Modbus 介紹 Modbus 是一種串行通信協議&#xff0c;用于連接工業自動化設備&#xff0c;最初由 Modicon 公司開發&#xff0c;誕生于 1979 年&#xff0c;現在已成為通用的通訊標準之一&#xff0c;廣泛用于工業自動化場景。 Modbus 采用主從模式&#xff0c;支持多種傳輸方…

PyTorch深度學習實戰(11)——卷積神經網絡

PyTorch深度學習實戰&#xff08;11&#xff09;——卷積神經網絡 0. 前言1. 全連接網絡的缺陷2. 卷積神經網絡基本組件2.1 卷積2.2 步幅和填充2.3 池化2.3 卷積神經網絡完整流程 3. 卷積和池化相比全連接網絡的優勢4. 使用 PyTorch 構建卷積神經網絡4.1 使用 PyTorch 構建 CNN…

H5移動端附件下載

目錄 H5移動端附件下載 1. 使用 window.open() 進行下載 2. 使用 a 標簽創建隱藏的可下載鏈接 3. 使用 iframe 進行下載 4. 使用 FileSaver.js 插件下載 4.1 Vue項目中導入并使用下載附件 4.2 FileSaver.js 的其他知識 H5移動端附件下載 1. 使用 window.open() 進行下載…

ClickHouse的數據類型

1.整數型 固定長度的整型&#xff0c;包括有符號整型或無符號整型。整型范圍&#xff08;-2n-1~2n-1-1&#xff09;&#xff1a; Int8 - [-128 : 127] Int16 - [-32768 : 32767] Int32 - [-2147483648 : 2147483647] Int64 - [-9223372036854775808 : 9223372036854775807]無符…

Linux學習之sed多行模式

N將下一行加入到模式空間 D刪除模式空間中的第一個字符到第一個換行符 P打印模式空間中的第一個字符到第一個換行符 doubleSpace.txt里邊的內容如下&#xff1a; goo d man使用下邊的命令可以實現把上邊對應的內容放到doubleSpace.txt。 echo goo >> doubleSpace.txt e…

sealos安裝k8s

一、前言 1、我前面文章有寫過使用 kubeadm 安裝的方式&#xff0c;大家可以去參考 &#xff08;二&#xff09;k8s集群安裝&#xff0c;有一系列的k8s文章說明 2、安裝k8s的方式有很多 kubeadmsealoskubespray等等 3、關于sealos來安裝 k8s &#xff0c;也是非常建議大家去…

Idea 反編譯jar包

實際項目中&#xff0c;有時候會需要更改jar包源碼來達到業務需求&#xff0c;本文章將介紹一下如何通過Idea來進行jar反編譯 1、Idea安裝decompiler插件 2、找到decompiler插件文件夾 decompiler插件文件夾路徑為&#xff1a;idea安裝路徑/plugins/java-decompiler/lib 3、…

可獨立創建應用的SaaS多租戶低代碼平臺之租戶的應用管理說明

在IT系統中&#xff0c;“租戶”&#xff08;tenant&#xff09;通常用于指代一種多租戶架構&#xff08;multi-tenancy&#xff09;&#xff0c;它是一種軟件架構模式&#xff0c;允許多個用戶或組織共享相同的應用程序或系統實例&#xff0c;但彼此之間的數據和配置被隔離開來…

C#軟件外包開發框架

C# 是一種由微軟開發的多范式編程語言&#xff0c;常用于開發各種類型的應用程序&#xff0c;從桌面應用程序到移動應用程序和Web應用程序。在 C# 開發中&#xff0c;有許多框架和庫可供使用&#xff0c;用于簡化開發過程、提高效率并實現特定的功能。下面和大家分享一些常見的…

代駕小程序怎么做

代駕小程序是一款專門為用戶提供代駕服務的手機應用程序。它具有以下功能&#xff1a; 1. 預約代駕&#xff1a;代駕小程序允許用戶在需要代駕服務時提前進行預約。用戶可以選擇出發地點、目的地以及預計用車時間&#xff0c;系統會自動匹配最合適的代駕司機&#xff0c;并確保…

黑馬B站八股文學習筆記

視頻地址&#xff1a;https://www.yuque.com/linxun-bpyj0/linxun/vy91es9lyg7kbfnr 大綱 基礎篇 基礎篇要點&#xff1a;算法、數據結構、基礎設計模式 1. 二分查找 要求 能夠用自己語言描述二分查找算法能夠手寫二分查找代碼能夠解答一些變化后的考法 算法描述 前提&a…

div 中元素居中的N種常用方法

本文主要記錄幾種常用的div盒子水平垂直都居中的方法。本文主要參考了該篇博文并實踐加以記錄說明以加深理解記憶 css之div盒子居中常用方法大全 本文例子使用的 html body結構下的div 盒子模型如下&#xff1a; <body><div class"container"><div c…

休息是不可能休息的

654.最大二叉樹 分析&#xff1a;相比較遍歷順序構建二叉樹&#xff0c;這個相對簡單。 思路&#xff1a;每次找到數組最大值&#xff0c;然后分割數組 class Solution { public:TreeNode*judge(vector<int>&nums){if(nums.size()0) return nullptr;int maxNum0,in…

Springboot 實踐(1)MyEclipse2019創建maven工程

項目講解步驟&#xff0c;基于本機已經正確安裝Java 1.8.0及MyEclipse2019的基礎之上&#xff0c;Java及MyEclipse的安裝&#xff0c;請參考其他相關文檔&#xff0c;Springboot 實踐文稿不再贅述。項目創建講解馬上開始。 一、首先打開MyEclipse2019&#xff0c;進入工作空間選…

Linux系統下安裝Git軟件

環境說明 Linux系統&#xff1a;CentOS 7.9 安裝GCC等 JDK版本&#xff1a;jdk-8u202-linux-x64.tar.gz Maven版本&#xff1a;apache-maven-3.8.8-bin.tar.gz 在以上環境下安裝Git&#xff08;git-2.41.0.tar.gz&#xff09;軟件。 查看是否安裝Git軟件 查看Git版本&#…

如何建設指標管理平臺,實現企業運營效率提升

隨著企業數字化轉型的深入推進&#xff0c;建設指標管理平臺已經成為企業數字化轉型的重要組成部分。 建設指標管理平臺可以幫助企業更好地了解業務數據和業務指標&#xff0c;實現數據可視化和智能化分析&#xff0c;提高企業的決策效率和管理水平。 在過去&#xff0c;企業通…