第 7 篇 : SpringBoot整合MinIO

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

<!-- MinIO -->
<dependency>
    <groupId>io.minio</groupId>
    <artifactId>minio</artifactId>
    <version>8.4.3</version>
</dependency>

注意 : 如果只添加上述依赖,会有问题,可以试一下
缺依赖报错
提示已经很明显了,直接点进去=>需要okthhp依赖,且版本不小于 4.8.1
依赖提示

<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
     <version>4.9.3</version>
</dependency>

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

post满请求
控制台可以看到上传的url
返回的url
直接请求会报错,因为Buckets是private,需要手动修改成public
直接请求报错

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

进入test
下载

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

修改权限

4.4 再次请求

1

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
要在Spring Boot中配置Minio的HTTPS访问,您需要完成以下步骤: 1. 生成自签名证书 使用以下命令生成自签名证书: ``` keytool -genkeypair -alias mycert -keyalg RSA -keysize 2048 -storetype PKCS12 -keystore keystore.p12 -validity 3650 -ext SAN=dns:localhost,ip:127.0.0.1 ``` 其中,`-ext SAN=dns:localhost,ip:127.0.0.1` 表示将 `localhost` 和 `127.0.0.1` 添加到证书的 SAN(Subject Alternative Name)字段中。 2. 在application.properties中配置Minio 在 `application.properties` 文件中添加以下配置: ``` # Minio配置 minio.endpoint=http://localhost:9000 minio.accessKey=accesskey minio.secretKey=secretkey minio.secure=true minio.ssl.trustStore=classpath:keystore.p12 minio.ssl.trustStorePassword=changeit minio.region=us-east-1 ``` 其中,`minio.secure=true` 表示启用HTTPS协议,`minio.ssl.trustStore` 和 `minio.ssl.trustStorePassword` 分别指定证书存储路径和密码。 3. 使用MinioClient 使用MinioClient连接到Minio服务器: ```java import io.minio.MinioClient; import io.minio.errors.MinioException; public class MinioDemo { public static void main(String[] args) throws MinioException { // 使用MinioClient连接到Minio服务器 MinioClient client = new MinioClient("https://localhost:9000", "accesskey", "secretkey"); // 列出所有存储桶 for (Bucket bucket : client.listBuckets()) { System.out.println(bucket.name()); } } } ``` 以上就是配置Minio的HTTPS访问的步骤,希望可以帮助到您。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

哈哈兽0026

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

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

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

打赏作者

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

抵扣说明:

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

余额充值