第 7 篇 : SpringBoot整合MinIO

1. 在redis项目中,增加MinIO依赖,刷新maven



    io.minio
    minio
    8.4.3

注意 : 如果只添加上述依赖,会有问题,可以试一下
第 7 篇 : SpringBoot整合MinIO_第1张图片
提示已经很明显了,直接点进去=>需要okthhp依赖,且版本不小于 4.8.1
第 7 篇 : SpringBoot整合MinIO_第2张图片


    com.squareup.okhttp3
    okhttp
     4.9.3

2. 在application.yml文件中添加MinIO配置

minio:
  endpoint: http://192.168.109.161:9000
  accessKey: root
  secretKey: root123456

3. 添加代码

3.1 SpringBean

package com.hahashou.test.redis.config;

import io.minio.MinioClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @description: Spring的Bean配置
 * @author: 哼唧兽
 * @date: 9999/9/21
 **/
@Configuration
public class SpringBean {

    @Value("${minio.endpoint}")
    private String endpoint;
    @Value("${minio.accessKey}")
    private String accessKey;
    @Value("${minio.secretKey}")
    private String secretKey;

    @Bean
    public MinioClient minioClient() {
        MinioClient minioClient = MinioClient.builder()
                        .endpoint(endpoint)
                        .credentials(accessKey, secretKey)
                        .build();
        return minioClient;
    }
}

3.2 新建utils包 , MinioUtils

package com.hahashou.test.redis.utils;

import io.minio.*;
import io.minio.errors.MinioException;
import io.minio.http.Method;
import io.minio.messages.Bucket;
import io.minio.messages.Item;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

/**
 * @description:
 * @author: 哼唧兽
 * @date: 9999/9/21
 **/
@Component
@Slf4j
public class MinioUtils {

    @Resource
    private MinioClient minioClient;

    /**
     * 查看存储bucket是否存在
     * @param bucketName
     * @return
     */
    public Boolean bucketExists(String bucketName) {
        Boolean found;
        try {
            found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        } catch (MinioException | InvalidKeyException | IOException | NoSuchAlgorithmException e) {
            log.error("Minio异常 : {}", e.getMessage());
            return null;
        }
        return found;
    }

    /**
     * 创建存储bucket
     * @param bucketName
     * @return
     */
    public boolean makeBucket(String bucketName) {
        try {
            minioClient.makeBucket(MakeBucketArgs.builder()
                    .bucket(bucketName)
                    .build());
        } catch (MinioException | InvalidKeyException | IOException | NoSuchAlgorithmException e) {
            log.error("Minio创建存储bucket异常 : {}", e.getMessage());
            return false;
        }
        return true;
    }

    /**
     * 删除存储bucket
     * @param bucketName
     * @return
     */
    public boolean removeBucket(String bucketName) {
        try {
            minioClient.removeBucket(RemoveBucketArgs.builder()
                    .bucket(bucketName)
                    .build());
        } catch (MinioException | InvalidKeyException | IOException | NoSuchAlgorithmException e) {
            log.error("Minio删除存储bucket异常 : {}", e.getMessage());
            return false;
        }
        return true;
    }

    /**
     * 获取全部bucket
     * @return
     */
    public List<Bucket> getAllBuckets() {
        try {
            return minioClient.listBuckets();
        } catch (MinioException | InvalidKeyException | IOException | NoSuchAlgorithmException e) {
            log.error("Minio获取全部bucket异常 : {}", e.getMessage());
        }
        return null;
    }

    /**
     * 文件上传
     * @param bucketName
     * @param fileName
     * @param multipartFile
     * @return
     */
    public String upload(String bucketName, String fileName, MultipartFile multipartFile) {
        if (!bucketExists(bucketName)) {
            makeBucket(bucketName);
        }
        try {
            InputStream inputStream = multipartFile.getInputStream();
            PutObjectArgs objectArgs = PutObjectArgs.builder()
                    .bucket(bucketName)
                    .object(fileName)
                    .stream(inputStream, multipartFile.getSize(), -1)
                    .contentType(multipartFile.getContentType())
                    .build();
            //文件名称相同会覆盖
            minioClient.putObject(objectArgs);
            inputStream.close();
            String fileUrl = preview(fileName, bucketName);
            return fileUrl.substring(0, fileUrl.indexOf("?"));
        } catch (MinioException | InvalidKeyException | IOException | NoSuchAlgorithmException e) {
            log.error("Minio文件上传异常 : {}", e.getMessage());
        }
        return null;
    }

    /**
     * 预览图片
     * @param fileName
     * @param bucketName
     * @return
     */
    public String preview(String fileName, String bucketName){
        // 查看文件地址
        GetPresignedObjectUrlArgs build = GetPresignedObjectUrlArgs
                .builder()
                .bucket(bucketName)
                .object(fileName)
                .method(Method.GET)
                .build();
        try {
            return minioClient.getPresignedObjectUrl(build);
        } catch (Exception e) {
            log.error("Minio预览图片异常 : {}", e.getMessage());
        }
        return null;
    }

    /**
     * 文件下载
     * @param fileName
     * @param bucketName
     * @param httpServletResponse
     */
    public void download(String fileName, String bucketName, HttpServletResponse httpServletResponse) {
        GetObjectArgs objectArgs = GetObjectArgs
                .builder()
                .bucket(bucketName)
                .object(fileName)
                .build();
        try (GetObjectResponse response = minioClient.getObject(objectArgs)){
            byte[] buf = new byte[1024];
            int len;
            try (FastByteArrayOutputStream os = new FastByteArrayOutputStream()){
                while ((len = response.read(buf)) != -1){
                    os.write(buf, 0, len);
                }
                os.flush();
                byte[] bytes = os.toByteArray();
                httpServletResponse.setCharacterEncoding("utf-8");
                //设置强制下载不打开
                //res.setContentType("application/force-download");
                httpServletResponse.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
                try (ServletOutputStream stream = httpServletResponse.getOutputStream()){
                    stream.write(bytes);
                    stream.flush();
                }
            }
        } catch (MinioException | InvalidKeyException | IOException | NoSuchAlgorithmException e) {
            log.error("Minio文件下载异常 : {}", e.getMessage());
        }
    }
    public byte[] downloadTest(String fileName, String bucketName, HttpServletResponse httpServletResponse) {
        GetObjectArgs objectArgs = GetObjectArgs
                .builder()
                .bucket(bucketName)
                .object(fileName)
                .build();
        try (GetObjectResponse response = minioClient.getObject(objectArgs)){
            byte[] buf = new byte[1024];
            int len;
            try (FastByteArrayOutputStream os = new FastByteArrayOutputStream()){
                while ((len = response.read(buf)) != -1){
                    os.write(buf, 0, len);
                }
                os.flush();
                return os.toByteArray();
            }
        } catch (MinioException | InvalidKeyException | IOException | NoSuchAlgorithmException e) {
            log.error("Minio文件下载异常 : {}", e.getMessage());
        }
        return new byte[0];
    }

    /**
     * 查看文件对象
     * @param bucketName
     * @return
     */
    public List<Item> listObjects(String bucketName) {
        Iterable<Result<Item>> results = minioClient.listObjects(ListObjectsArgs.builder().bucket(bucketName).build());
        List<Item> items = new ArrayList<>();
        try {
            for (Result<Item> result : results) {
                items.add(result.get());
            }
        } catch (MinioException | InvalidKeyException | IOException | NoSuchAlgorithmException e) {
            log.error("Minio查看文件对象异常 : {}", e.getMessage());
            return items;
        }
        return items;
    }
}

3.3 MinioController

package com.hahashou.test.redis.controller;

import com.hahashou.test.redis.utils.MinioUtils;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @description: 测试MinIO
 * @author: 哼唧兽
 * @date: 9999/9/21
 **/
@RestController
@RequestMapping("/minio")
@Api(tags = "测试MinIO")
@Slf4j
public class MinioController {

    public static final String TEST = "test";

    @Resource
    private MinioUtils minioUtils;

    @PostMapping("/upload")
    public void upload(final HttpServletRequest httpServletRequest) {
        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) httpServletRequest;
        List<MultipartFile> multipartFileList = multipartHttpServletRequest.getFiles("file");
        if (!CollectionUtils.isEmpty(multipartFileList)) {
            // 只上传第一个
            MultipartFile wall = multipartFileList.get(0);
            String originalFilename = wall.getOriginalFilename();
            // 同名会覆盖
            log.info("文件名称 : {}", originalFilename);
            String minioUrl = minioUtils.upload(TEST, originalFilename, wall);
            log.info("上传到Minio的url : {}", minioUrl);
        }
    }
}

4. 上传以及下载

4.1 上传到minio

第 7 篇 : SpringBoot整合MinIO_第3张图片
控制台可以看到上传的url
第 7 篇 : SpringBoot整合MinIO_第4张图片
直接请求会报错,因为Buckets是private,需要手动修改成public
第 7 篇 : SpringBoot整合MinIO_第5张图片

4.2 登录minio控制台,下载查看

进入test
第 7 篇 : SpringBoot整合MinIO_第6张图片

4.3 设置在右上角,修改Buckets为public(实际开发不修改)

第 7 篇 : SpringBoot整合MinIO_第7张图片

4.4 再次请求

你可能感兴趣的:(SpringBoot,spring,boot,java,后端)