最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

SpringBoot集成MinIO的示例代碼

 更新時間:2023年06月30日 09:12:48   作者:路在何方い  
對象存儲服務(wù)OSS是一種海量、安全、低成本、高可靠的云存儲服務(wù),適合存放任意類型的文件,這篇文章主要介紹了SpringBoot集成MinIO的示例代碼,需要的朋友可以參考下

簡介

對象存儲服務(wù)OSS(Object Storage Service)是一種海量、安全、低成本、高可靠的云存儲服務(wù),適合存放任意類型的文件。容量和處理能力彈性擴展,多種存儲類型供選擇,全面優(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
# 自定義配置項,方便在代碼中使用
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開頭的配置項*/
@ConfigurationProperties(prefix = "minio")
public class MinioConfig {
    /*會自動的對應(yī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 進行添加
            /**
             *   參數(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)文章

  • InputStreamReader 和FileReader的區(qū)別及InputStream和Reader的區(qū)別

    InputStreamReader 和FileReader的區(qū)別及InputStream和Reader的區(qū)別

    這篇文章主要介紹了InputStreamReader 和FileReader的區(qū)別及InputStream和Reader的區(qū)別的相關(guān)資料,需要的朋友可以參考下
    2015-12-12
  • java中的Io(input與output)操作總結(jié)(二)

    java中的Io(input與output)操作總結(jié)(二)

    這一節(jié)我們來討論關(guān)于文件自身的操作包括:創(chuàng)建文件對象、創(chuàng)建和刪除文件、文件的判斷和測試、創(chuàng)建目錄、獲取文件信息、列出文件系統(tǒng)的根目錄、列出目錄下的所有文件,等等,感興趣的朋友可以了解下
    2013-01-01
  • Java 詳細講解線程安全與同步附實例與注釋

    Java 詳細講解線程安全與同步附實例與注釋

    線程安全是多線程編程時的計算機程序代碼中的一個概念。在擁有共享數(shù)據(jù)的多條線程并行執(zhí)行的程序中,線程安全的代碼會通過同步機制保證各個線程都可以正常且正確的執(zhí)行,不會出現(xiàn)數(shù)據(jù)污染等意外情況
    2022-04-04
  • Springmvc請求參數(shù)類型轉(zhuǎn)換器及原生api代碼實例

    Springmvc請求參數(shù)類型轉(zhuǎn)換器及原生api代碼實例

    這篇文章主要介紹了Springmvc請求參數(shù)類型轉(zhuǎn)換器及原生api代碼實例,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-10-10
  • SpringBoot Freemarker基礎(chǔ)配置與使用方式

    SpringBoot Freemarker基礎(chǔ)配置與使用方式

    文章主要介紹了在Spring Boot項目中使用FreeMarker模板引擎的基礎(chǔ)配置、使用方法和注意事項,包括依賴引入、配置文件設(shè)置、數(shù)據(jù)類型調(diào)用、運算符支持、時間格式轉(zhuǎn)換、邏輯表達式等
    2026-05-05
  • Java對象轉(zhuǎn)Json,關(guān)于@JSONField對象字段重命名和順序問題

    Java對象轉(zhuǎn)Json,關(guān)于@JSONField對象字段重命名和順序問題

    這篇文章主要介紹了Java對象轉(zhuǎn)Json,關(guān)于@JSONField對象字段重命名和順序問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-08-08
  • springboot打成jar后獲取classpath下文件失敗的解決方案

    springboot打成jar后獲取classpath下文件失敗的解決方案

    這篇文章主要介紹了使用springboot打成jar后獲取classpath下文件失敗的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-08-08
  • Java中的main函數(shù)的詳細介紹

    Java中的main函數(shù)的詳細介紹

    這篇文章主要介紹了Java中的main函數(shù)的詳細介紹的相關(guān)資料,main()函數(shù)在java程序中必出現(xiàn)的函數(shù),這里就講解下使用方法,需要的朋友可以參考下
    2017-09-09
  • Idea中添加Maven項目支持scala的詳細步驟

    Idea中添加Maven項目支持scala的詳細步驟

    這篇文章主要介紹了Idea中添加Maven項目支持scala,本文通過圖文并茂的形式給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2023-03-03
  • Java ==,equals()與hashcode()的使用

    Java ==,equals()與hashcode()的使用

    本文主要介紹了Java ==,equals()與hashcode()的使用,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-05-05

最新評論

彰武县| 郁南县| 斗六市| 龙南县| 山丹县| 宝清县| 雅江县| 阳信县| 于田县| 富川| 睢宁县| 武穴市| 会东县| 阳春市| 富阳市| 汝南县| 临夏市| 巴马| 息烽县| 呼图壁县| 镇安县| 胶南市| 三江| 祁东县| 长葛市| 海丰县| 南汇区| 肃宁县| 宾阳县| 合水县| 观塘区| 麦盖提县| 辽中县| 丰县| 蕉岭县| 柏乡县| 邻水| 河间市| 崇信县| 铜陵市| 玉树县|