SpringBoot整合minio

1. 下载及安装

1.1 windows版本

目录结构
在这里插入图片描述

启动文件
在这里插入图片描述
在这里插入图片描述
标红的地方按实际安装地更改

@echo off
REM 声明采用UTF-8编码
chcp 65001
echo.
echo [信息] 运行MinIO文服务器。
echo.
:: 设置窗口标题
title Minio文件服务

:: 设置用户名为myname
setx MINIO_ROOT_USER minio
:: 设置密码为mypassword
setx MINIO_ROOT_PASSWORD minio123
 
cd %~dp0
:: 切换到minio.exe文件所在目录
cd D:\dev\minio\bin
:: 启动minio服务
minio.exe server D:\dev\minio\data --console-address ":9001" --address ":9000" > D:\dev\minio\logs\minio.log
pause

1.2 Linux版本

待更新

2. SpringBoot整合minio

2.1 依赖

        <dependency>
            <groupId>io.minio</groupId>
            <artifactId>minio</artifactId>
            <version>8.2.1</version>
            <exclusions>
                <exclusion>
                    <groupId>com.squareup.okhttp3</groupId>
                    <artifactId>okhttp</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.jetbrains.kotlin</groupId>
                    <artifactId>kotlin-stdlib</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>4.9.0</version>
        </dependency>

2.2 配置文件

minio:
  url: http://127.0.0.1:9000 #Minio服务所在地址
  bucketName: zld #存储桶名称
  accessKey: minio #访问的key
  secretKey: minio123 #访问的秘钥

2.3 配置类

package com.ruoyi.minio.config;

import io.minio.MinioClient;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@ConfigurationProperties(prefix = "minio")
public class MinioConfig {
    /**
     * minio服务器地址
     */
    private String url;
    /**
     * 用户名
     */
    private String accessKey;
    /**
     * 密码
     */
    private String secretKey;
    /**
     * 密码
     */
    private String bucketName;

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getAccessKey() {
        return accessKey;
    }

    public void setAccessKey(String accessKey) {
        this.accessKey = accessKey;
    }

    public String getSecretKey() {
        return secretKey;
    }

    public void setSecretKey(String secretKey) {
        this.secretKey = secretKey;
    }

    public String getBucketName() {
        return bucketName;
    }

    public void setBucketName(String bucketName) {
        this.bucketName = bucketName;
    }

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


2.4 工具类

package com.ruoyi.minio.util;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.minio.config.MinioConfig;
import io.minio.*;
import io.minio.errors.*;
import io.minio.http.Method;
import io.minio.messages.Bucket;
import io.minio.messages.DeleteError;
import io.minio.messages.Item;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
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;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Component
public class MinioUtil {
    @Autowired
    private MinioConfig prop;

    @Resource
    private MinioClient minioClient;

    /**
     * 查看存储bucket是否存在
     *
     * @return boolean
     */
    public Boolean bucketExists(String bucketName) {
        Boolean found;
        try {
            found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return found;
    }

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

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

    /**
     * 获取全部bucket
     */
    public List<Bucket> getAllBuckets() {
        try {
            List<Bucket> buckets = minioClient.listBuckets();
            return buckets;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 文件上传
     *
     * @param file 文件
     * @return Boolean
     */
    public String upload(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        if (StringUtils.isBlank(originalFilename)) {
            throw new RuntimeException();
        }
        String fileName = IdUtils.simpleUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
        String objectName = DateUtils.datePath() + "/" + fileName;
        try {
            PutObjectArgs objectArgs = PutObjectArgs.builder().bucket(prop.getBucketName()).object(objectName)
                    .stream(file.getInputStream(), file.getSize(), -1).contentType(file.getContentType()).build();
            //文件名称相同会覆盖
            minioClient.putObject(objectArgs);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return objectName;
    }

    /**
     * 文件上传
     *
     * @param bucketName
     * @param fileName
     * @param multipartFile
     * @return
     * @throws IOException
     */
    public String uploadFile(String bucketName, String fileName, MultipartFile multipartFile) throws IOException {
        String url = "";
        MinioClient minioClient = SpringUtils.getBean(MinioClient.class);
        try (InputStream inputStream = multipartFile.getInputStream()) {
            boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (!found) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
                /**
                 * bucket权限-读写
                 */
                String READ_WRITE = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":[\"*\"]},\"Action\":[\"s3:GetBucketLocation\",\"s3:ListBucket\",\"s3:ListBucketMultipartUploads\"],\"Resource\":[\"arn:aws:s3:::" + bucketName + "\"]},{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":[\"*\"]},\"Action\":[\"s3:DeleteObject\",\"s3:GetObject\",\"s3:ListMultipartUploadParts\",\"s3:PutObject\",\"s3:AbortMultipartUpload\"],\"Resource\":[\"arn:aws:s3:::" + bucketName + "/*\"]}]}";
                minioClient.setBucketPolicy(SetBucketPolicyArgs.builder().bucket(bucketName).config(READ_WRITE).build());
            }
            minioClient.putObject(PutObjectArgs.builder().bucket(bucketName)
                    .object(fileName)
                    .stream(inputStream, multipartFile.getSize(), -1)
                    .contentType(multipartFile.getContentType()).build()
            );
            //路径获取
            url = minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder().bucket(bucketName).object(fileName).
                    method(Method.GET).build());
            url = url.substring(0, url.indexOf('?'));
            //常规访问路径获取
            return url;
        } catch (Exception e) {
            throw new IOException(e.getMessage(), e);
        }
    }

    /**
     * 预览图片
     *
     * @param fileName
     * @return
     */
    public String preview(String fileName) {
        // 查看文件地址
        GetPresignedObjectUrlArgs build = new GetPresignedObjectUrlArgs().builder().bucket(prop.getBucketName()).object(fileName).method(Method.GET).build();
        try {
            String url = minioClient.getPresignedObjectUrl(build);
            return url;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 文件下载
     *
     * @param fileName 文件名称
     * @param res      response
     * @return Boolean
     */
    public void download(String fileName, HttpServletResponse res) {
        GetObjectArgs objectArgs = GetObjectArgs.builder().bucket(prop.getBucketName())
                .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();
                res.setCharacterEncoding("utf-8");
                // 设置强制下载不打开
                // res.setContentType("application/force-download");
                res.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
                try (ServletOutputStream stream = res.getOutputStream()) {
                    stream.write(bytes);
                    stream.flush();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 查看文件对象
     *
     * @return 存储bucket内文件对象信息
     */
    public List<Item> listObjects() {
        Iterable<Result<Item>> results = minioClient.listObjects(
                ListObjectsArgs.builder().bucket(prop.getBucketName()).build());
        List<Item> items = new ArrayList<>();
        try {
            for (Result<Item> result : results) {
                items.add(result.get());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return items;
    }

    /**
     * 删除
     *
     * @param fileName
     * @return
     * @throws Exception
     */
    public boolean remove(String fileName) {
        try {
            minioClient.removeObject(RemoveObjectArgs.builder().bucket(prop.getBucketName()).object(fileName).build());
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    /**
     * 删除文件夹及文件
     *
     * @param bucketName bucket名称
     * @param objectName 文件或文件夹名称:以.结尾为文件,以/结尾为文件夹
     * @since tarzan LIU
     */
    public boolean deleteObjects(String bucketName, String objectName) {
        if (StringUtils.isNotBlank(objectName)) {
            if (objectName.endsWith(".") || objectName.endsWith("/")) {
                Iterable<Result<Item>> list = minioClient.listObjects(ListObjectsArgs.builder().bucket(bucketName).prefix(objectName).recursive(true).build());
                ExecutorService executorService = Executors.newFixedThreadPool(10);
                list.forEach(e -> {
                    executorService.execute(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                minioClient.removeObject(RemoveObjectArgs.builder().bucket(bucketName).object(e.get().objectName()).build());
                            } catch (ErrorResponseException ex) {
                                throw new RuntimeException(ex);
                            } catch (InsufficientDataException ex) {
                                throw new RuntimeException(ex);
                            } catch (InternalException ex) {
                                throw new RuntimeException(ex);
                            } catch (InvalidKeyException ex) {
                                throw new RuntimeException(ex);
                            } catch (InvalidResponseException ex) {
                                throw new RuntimeException(ex);
                            } catch (IOException ex) {
                                throw new RuntimeException(ex);
                            } catch (NoSuchAlgorithmException ex) {
                                throw new RuntimeException(ex);
                            } catch (ServerException ex) {
                                throw new RuntimeException(ex);
                            } catch (XmlParserException ex) {
                                throw new RuntimeException(ex);
                            }
                        }
                    });
                });
                executorService.shutdown();
                return true;
            }
        }
        return true;
    }
}


2.5 测试

1. 业务层

package com.ruoyi.minio.service;

import org.springframework.web.multipart.MultipartFile;

/**
 * minio服务
 */
public interface MinioService {
    /**
     * 文件上传
     *
     * @param file
     * @return
     */
    public String upload(MultipartFile file);

    /**
     * 文件上传
     *
     * @param file
     * @return
     */
    public String uploadFile(String bucketName, String fileName, MultipartFile multipartFile);

    /**
     * 预览图片
     * @param fileName
     * @return
     */
    public String preview(String fileName);
    /**
     * 文件删除
     *
     * @param fileName
     * @return
     */
    public boolean remove(String fileName);

    /**
     * 删除文件夹及文件
     *
     * @param bucketName bucket名称
     * @param objectName 文件或文件夹名称
     * @since tarzan LIU
     */
    public boolean deleteObjects(String bucketName, String objectName);

    /**
     * 删除前几天文件夹
     * @param bucketName
     * @param day
     * @return
     */
    boolean deleteObjectsByDay(String bucketName, int day);
}

package com.ruoyi.minio.service.impl;

import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.minio.service.MinioService;
import com.ruoyi.minio.util.MinioUtil;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;

@Service
public class MinioServiceImpl implements MinioService {
    @Resource
    private MinioUtil minioUtil;

    /**
     * 文件上传
     *
     * @param file
     * @return
     */
    @Override
    public String upload(MultipartFile file) {
        return minioUtil.upload(file);
    }

    /**
     * 文件上传
     *
     * @param bucketName
     * @param fileName
     * @param multipartFile
     * @return
     */
    @Override
    public String uploadFile(String bucketName, String fileName, MultipartFile multipartFile) {
        try {
            return minioUtil.uploadFile(bucketName, fileName, multipartFile);
        } catch (IOException e) {
            throw new ServiceException("上传失败,请联系管理员");
        }
    }

    /**
     * 预览图片
     *
     * @param fileName
     * @return
     */
    @Override
    public String preview(String fileName) {
        return minioUtil.preview(fileName);
    }

    /**
     * 文件删除
     *
     * @param fileName
     * @return
     */
    @Override
    public boolean remove(String fileName) {
        return minioUtil.remove(fileName);
    }

    /**
     * 删除文件夹及文件
     *
     * @param bucketName bucket名称
     * @param objectName 文件或文件夹名称
     * @since tarzan LIU
     */
    @Override
    public boolean deleteObjects(String bucketName, String objectName) {
        return minioUtil.deleteObjects(bucketName, objectName);
    }

    /**
     * 删除前几天文件夹
     *
     * @param bucketName
     * @param day
     * @return
     */
    @Override
    public boolean deleteObjectsByDay(String bucketName, int day) {
        String objectName = DateUtils.getDayAgoOrAfterString(day)+"/";
        return minioUtil.deleteObjects(bucketName, objectName);
    }
}

2. 控制层

package com.ruoyi.web.controller.minio;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.minio.service.MinioService;
import org.springframework.web.bind.annotation.GetMapping;
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 javax.annotation.Resource;

/**
 * minio文件管理
 */
@RestController
@RequestMapping("/minio")
public class MinioController {

    @Resource
    public MinioService minioService;

    @PostMapping("/upload")
    public AjaxResult upload(MultipartFile file) {
        String upload = minioService.upload(file);
        return AjaxResult.success(upload);
    }

    /**
     * 预览图片
     *
     * @param fileName
     * @return
     */
    @GetMapping("/preview")
    public AjaxResult preview(String fileName) {
        String preview = minioService.preview(fileName);
        return AjaxResult.success(preview);
    }

    /**
     * 删除文件
     *
     * @param fileName
     * @return
     */
    @GetMapping("/remove")
    public AjaxResult remove(String fileName) {
        return AjaxResult.success(minioService.remove(fileName));
    }

    /**
     * 删除文件夹及文件
     *
     * @param bucketName bucket名称
     * @param objectName 文件或文件夹名称
     * @since tarzan LIU
     */
    @GetMapping("/deleteObjects")
    public AjaxResult deleteObjects(String bucketName, String objectName) {
        return AjaxResult.success(minioService.deleteObjects(bucketName, objectName));
    }

    /**
     * 删除文件夹及文件
     *
     * @param bucketName bucket名称
     * @param objectName 文件或文件夹名称
     * @since tarzan LIU
     */
    @GetMapping("/deleteObjectsByDay")
    public AjaxResult deleteObjectsByDay(String bucketName, int day) {
        return AjaxResult.success(minioService.deleteObjectsByDay(bucketName, day));
    }
}

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
发出的红包

打赏作者

与海boy

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值