SpringBoot集成MinIO

简介

对象存储服务OSS(Object Storage Service)是一种海量、安全、低成本、高可靠的云存储服务,适合存放任意类型的文件。容量和处理能力弹性扩展,多种存储类型供选择,全面优化存储成本。今天我这里主要讲解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 {
    /*会自动的对应配置项中对应的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) {
            //往桶中添加数据   minioClient 进行添加

            /**
             *   参数1: 桶的名称
             *   参数2: 文件的名称
             *   参数3: 文件的流
             *   参数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;
    }

    /**
     * 获取对象的元数据
     * @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;
    }

}

上传接口调用

 下载接口调用

 

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot项目中集成Minio,你可以按照以下步骤进行操作: 1. 首先,你需要在项目的pom.xml文件中添加Minio的依赖项。你可以使用以下代码片段来添加依赖项: ``` <dependency> <groupId>io.minio</groupId> <artifactId>minio</artifactId> <version>8.5.1</version> </dependency> ``` 2. 接下来,你需要在你的应用程序中使用Minio的API进行连接和操作。你可以参考以下代码片段来完成这一步骤: ```java import io.minio.MinioClient; // 创建MinioClient对象 MinioClient minioClient = new MinioClient("http://localhost:9000", "access-key", "secret-key"); // 检查存储桶是否存在 boolean isExist = minioClient.bucketExists("bucket-name"); if (isExist) { System.out.println("存储桶已存在!"); } else { // 创建存储桶 minioClient.makeBucket("bucket-name"); System.out.println("存储桶创建成功!"); } ``` 3. 最后,你需要在你的应用程序的配置文件(例如application.yml或application.properties)中配置Minio的连接信息。你可以参考以下代码片段来完成这一步骤: ```yaml minio: url: 129.0.0.1:9000 # 替换成你自己的Minio服务端地址 access-key: minioadmin secret-key: minioadmin bucket-name: ding_server ``` 这样,你就成功地集成Minio到你的Spring Boot项目中,并可以使用Minio的API进行对象存储操作了。记得替换相应的连接信息和存储桶名称以适应你的项目需求。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [Springboot集成Minio](https://blog.csdn.net/qq_45374325/article/details/129464067)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] - *2* *3* [springboot整合minio](https://blog.csdn.net/qq_36090537/article/details/128100423)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值