Spring Boot 整合MinIo文件服务

Spring Boot 整合MinIo文件服务

话不多说,直接上代码,windows示例,Linux等同

第一步,下载安装MinIO
MinIO官网

第二步,启动MinIO
进入到MinIO文件目录中新建一个文件夹,用于存放上传得资源
文件夹名称 暂定为minioData在这里插入图片描述
当前目录进入cmd 执行
minio.exe server F:\toolsAll\monio\minioData --存放路径根据各自得路径指定即可,不报错代表启动成功,可以访问http://127.0.0.1:9000 进行登录
默认账号密码都是minioadmin
Spring Boot 整合MinIo文件服务_第1张图片
buckets就是桶的意思,多业务多桶存储可以指定不同的桶即可
Spring Boot 整合MinIo文件服务_第2张图片

后端代码

pom增加依赖

    <dependency>
            <groupId>io.minio</groupId>
            <artifactId>minio</artifactId>
            <version>8.4.3</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
            <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
          <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
            <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13</version>
        </dependency>

yml文件

server:
  port: 8888
# minio 参数配置
minio:
  endpoint: http://localhost:9000/
  accessKey: minioadmin
  secretKey: minioadmin
  buckets: test

test测试类,记录常用方法

package com.example.demo;

import com.example.demo.util.ObjectItem;
import io.minio.BucketExistsArgs;
import io.minio.GetObjectArgs;
import io.minio.ListObjectsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.RemoveBucketArgs;
import io.minio.RemoveObjectsArgs;
import io.minio.Result;
import io.minio.UploadObjectArgs;
import io.minio.messages.DeleteError;
import io.minio.messages.DeleteObject;
import io.minio.messages.Item;
import org.apache.commons.compress.utils.IOUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @description: minioTest类
 * @version
 */
public class MinioTest {

    private String bucketName = "test1";
    private String endpoint = "http://localhost:9000/";
    private String accessKey = "minioadmin";
    private String secretKey = "minioadmin";

    /**
     * 业务代码中一般都是读取配置文件进行连接
     *
     * @return
     */
    public MinioClient reload() {
        return MinioClient.builder()
                .endpoint(endpoint)
                .credentials(accessKey, secretKey)
                .build();
    }

    /**
     * description: 判断bucket是否存在,不存在则创建
     *
     * @return: void
     */
    @Test
    public void existBucket() {
        MinioClient minioClient = reload();
        try {
            boolean exists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (!exists) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 创建存储bucket
     *
     * @param bucketName 存储bucket名称
     * @return Boolean
     */
    public Boolean makeBucket(String bucketName) {
        MinioClient minioClient = reload();
        try {
            minioClient.makeBucket(MakeBucketArgs.builder()
                    .bucket(bucketName)
                    .build());
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 删除存储bucket
     *
     * @param bucketName 存储bucket名称
     * @return Boolean
     */
    public Boolean removeBucket(String bucketName) {
        MinioClient minioClient = reload();
        try {
            minioClient.removeBucket(RemoveBucketArgs.builder()
                    .bucket(bucketName)
                    .build());
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * description: 上传文件
     *
     * @return: java.lang.String
     */
    @Test
    public void upload() {
        MinioClient minioClient = reload();
        try {
            //本地文件上传
            minioClient.uploadObject(
                    UploadObjectArgs.builder()
                            .bucket(bucketName)
                            .object("测试模板.docx")
                            .filename("F:\\测试模板.docx") // 本地磁盘的路径
                            .build());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * description: 下载文件
     *
     * @param fileName
     * @return: org.springframework.http.ResponseEntity
     */
    public ResponseEntity<byte[]> download(String fileName) {
        MinioClient minioClient = reload();
        ResponseEntity<byte[]> responseEntity = null;
        InputStream in = null;
        ByteArrayOutputStream out = null;
        try {
            in = minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(fileName).build());
            out = new ByteArrayOutputStream();
            IOUtils.copy(in, out);
            //封装返回值
            byte[] bytes = out.toByteArray();
            HttpHeaders headers = new HttpHeaders();
            try {
                headers.add("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            headers.setContentLength(bytes.length);
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setAccessControlExposeHeaders(Arrays.asList("*"));
            responseEntity = new ResponseEntity<byte[]>(bytes, headers, HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return responseEntity;
    }
}

运行创建桶和上传之后我们的minio上面已经有一个桶和一个文件了,该篇基础教程到此就结束了,剩下的无非就是把minio连接写到配置中,启动服务自动连接,上传文件之前校验桶是否存在等等,对你有帮助请点赞评论支持一下。
Spring Boot 整合MinIo文件服务_第3张图片

你可能感兴趣的:(minio,spring,boot,java,spring)