SpringBoot集成MinIO的示例代碼
簡介
對象存儲服務(wù)OSS(Object Storage Service)是一種海量、安全、低成本、高可靠的云存儲服務(wù),適合存放任意類型的文件。容量和處理能力彈性擴(kuò)展,多種存儲類型供選擇,全面優(yōu)化存儲成本。今天我這里主要講解SpringBoot如何集成MinIO。
引入依賴
<dependency>
<groupId>io.minio</groupId>
<artifactId>minio</artifactId>
<version>7.0.2</version>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.14.9</version>
<scope>compile</scope>
</dependency>yml文件配置
# Tomcat
server:
port: 9100
# 自定義配置項(xiàng),方便在代碼中使用
minio:
endpoint: 127.0.0.1
port: 9001
accessKey: minioadmin
secretKey: minioadmin
bucketName: upload
spring:
servlet:
multipart:
max-file-size: 10000MB
max-request-size: 20000MB編寫配置類
package com.example.mimio.config;
import io.minio.MinioClient;
import io.minio.errors.InvalidEndpointException;
import io.minio.errors.InvalidPortException;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Data
@Configuration
/*加載yml文件中以minio開頭的配置項(xiàng)*/
@ConfigurationProperties(prefix = "minio")
public class MinioConfig {
/*會自動的對應(yīng)配置項(xiàng)中對應(yīng)的key*/
private String endpoint;//minio.endpoint
private String accessKey;
private String secretKey;
private Integer port;
/*把官方提供的MinioClient客戶端注冊到IOC容器中*/
@Bean
public MinioClient getMinioClient() throws InvalidPortException, InvalidEndpointException {
MinioClient minioClient = new MinioClient(getEndpoint(), getPort(), getAccessKey(), getSecretKey(), false);
return minioClient;
}
}編寫工具類
package com.example.mimio.util;
import io.minio.MinioClient;
import io.minio.ObjectStat;
import io.minio.PutObjectOptions;
import io.minio.Result;
import io.minio.errors.*;
import io.minio.messages.DeleteError;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
@Component
public class MinioClientUtil {
@Value("${minio.bucketName}")
private String bucketName;
@Resource
private MinioClient minioClient;
private static final int DEFAULT_EXPIRY_TIME = 7 * 24 * 3600;
/**
* 檢查存儲桶是否存在
*/
public boolean bucketExists(String bucketName) throws InvalidKeyException, ErrorResponseException,
IllegalArgumentException, InsufficientDataException, InternalException, InvalidBucketNameException,
InvalidResponseException, NoSuchAlgorithmException, XmlParserException, IOException {
boolean flag = minioClient.bucketExists(this.bucketName);
if (flag) return true;
return false;
}
/**
* 通過InputStream上傳對象
*
* @param objectName 存儲桶里的對象名稱
* @param stream 要上傳的流 (文件的流)
*/
public boolean putObject(String objectName, InputStream stream) throws Exception {
//判斷 桶是否存在
boolean flag = bucketExists(bucketName);
if (flag) {
//往桶中添加數(shù)據(jù) minioClient 進(jìn)行添加
/**
* 參數(shù)1: 桶的名稱
* 參數(shù)2: 文件的名稱
* 參數(shù)3: 文件的流
* 參數(shù)4: 添加的配置
*/
minioClient.putObject(bucketName, objectName, stream, new PutObjectOptions(stream.available(), -1));
ObjectStat statObject = statObject(objectName);
if (statObject != null && statObject.length() > 0) {
return true;
}
}
return false;
}
/**
* 刪除一個對象
* @param objectName 存儲桶里的對象名稱
*/
public boolean removeObject(String objectName)throws Exception {
boolean flag = bucketExists(bucketName);
if (flag) {
minioClient.removeObject(bucketName, objectName);
return true;
}
return false;
}
/**
* 刪除指定桶的多個文件對象,返回刪除錯誤的對象列表,全部刪除成功,返回空列表
* @param objectNames 含有要刪除的多個object名稱的迭代器對象
*/
public List<String> removeObject(List<String> objectNames) throws Exception {
List<String> deleteErrorNames = new ArrayList<>();
boolean flag = bucketExists(bucketName);
if (flag) {
Iterable<Result<DeleteError>> results = minioClient.removeObjects(bucketName, objectNames);
for (Result<DeleteError> result : results) {
DeleteError error = result.get();
deleteErrorNames.add(error.objectName());
}
}
return deleteErrorNames;
}
/**
* 獲取對象的元數(shù)據(jù)
* @param objectName 存儲桶里的對象名稱
*/
public ObjectStat statObject(String objectName) throws Exception {
boolean flag = bucketExists(bucketName);
if (flag) {
ObjectStat statObject = minioClient.statObject(bucketName, objectName);
return statObject;
}
return null;
}
/**
* 文件訪問路徑
* @param objectName 存儲桶里的對象名稱
*/
public String getObjectUrl(String objectName) throws Exception {
boolean flag = bucketExists(bucketName);
String url = "";
if (flag) {
url = minioClient.getObjectUrl(bucketName, objectName);
}
return url;
}
public void getObject(String filename, HttpServletResponse response){
InputStream in = null;
OutputStream out = null;
try{
in=minioClient.getObject(bucketName,filename);
int length=0;
byte[] buffer = new byte[1024];
out = response.getOutputStream();
response.reset();
response.addHeader("Content-Disposition",
" attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
response.setContentType("application/octet-stream");
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
}catch (Exception e){
e.printStackTrace();
}finally {
if (in != null){
try {
in.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
編寫控制器
package com.example.mimio.controller;
import com.example.mimio.response.ResponseData;
import com.example.mimio.util.MinioClientUtil;
import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;
@RestController
public class TestController {
@Autowired
public void setMinioClientUtil(MinioClientUtil minioClientUtil) {
this.minioClientUtil = minioClientUtil;
}
private MinioClientUtil minioClientUtil;
@PostMapping("/upload")
public ResponseData uploadMinio(@RequestPart MultipartFile file) throws Exception {
//拿到圖片 MultipartFile封裝接受的類
//拿到圖片的名稱
String filename = file.getOriginalFilename();
//拿到圖片的 UUId + 圖片類型 (解決圖片重名的問題 )
String uuid = UUID.randomUUID().toString();
String imgType = filename.substring(filename.lastIndexOf("."));
//圖片文件的新名稱 xxx/uuid.jpg 圖片拼接后的名
String fileName = uuid + imgType;
boolean flag = minioClientUtil.putObject(fileName, file.getInputStream());
String path = "/upload/" + fileName;
return flag ? ResponseData.success("上傳成功",path):ResponseData.failed("上傳失敗");
}
@PostMapping("/downLoad")
public ResponseData downLoadMinio(String url,HttpServletResponse response) throws Exception {
// String objectUrl = minioClientUtil.getObjectUrl("a9e203f9-1bbb-4d59-8c28-3a183c064502.sql")
String trim = url.trim();
String path = trim.substring(trim.indexOf("/", 1), trim.length());
minioClientUtil.getObject(path,response);
return null;
}
}上傳接口調(diào)用

下載接口調(diào)用

到此這篇關(guān)于SpringBoot集成MinIO的文章就介紹到這了,更多相關(guān)SpringBoot集成MinIO內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
maven項(xiàng)目下solr和spring的整合配置詳解
這篇文章主要介紹了maven項(xiàng)目下solr和spring的整合配置詳解,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-11-11
java實(shí)現(xiàn)發(fā)送郵箱驗(yàn)證碼
這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)發(fā)送郵箱驗(yàn)證碼,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-08-08
springboot自定義校驗(yàn)注解的實(shí)現(xiàn)過程
這篇文章主要介紹了springboot自定義校驗(yàn)注解的實(shí)現(xiàn)過程,本文結(jié)合示例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友參考下吧2023-11-11
String s = new String(''a '') 到底產(chǎn)生幾個對象
這篇文章主要介紹了String s = new String(" a ") 到底產(chǎn)生幾個對象,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-05-05
Java使用LinkedHashMap進(jìn)行分?jǐn)?shù)排序
這篇文章主要介紹了Java使用LinkedHashMap進(jìn)行分?jǐn)?shù)排序的相關(guān)代碼,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-05-05
如何基于sqlite實(shí)現(xiàn)kafka延時消息詳解
這篇文章主要給大家介紹了關(guān)于如何基于sqlite實(shí)現(xiàn)kafka延時消息的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2022-01-01

