SpringBoot整合Minio

SpringBoot整合Minio

一、添加依赖

<parent>
	<artifactId>spring-boot-starter-parentartifactId>
	<groupId>org.springframework.bootgroupId>
	<version>2.6.6version>
parent>
<dependencyManagement>
	<dependencies>
		<dependency>
			<groupId>org.springframework.cloudgroupId>
			<artifactId>spring-cloud-dependenciesartifactId>
			<version>2021.0.1version>
			<type>pomtype>
			<scope>importscope>
		dependency>
	dependencies>
dependencyManagement>
<dependencies>
	<dependency>
		<groupId>org.springframework.bootgroupId>
		<artifactId>spring-boot-starter-webartifactId>
	dependency>
	<dependency>
		<groupId>org.springframework.cloudgroupId>
		<artifactId>spring-cloud-starter-consul-configartifactId>
	dependency>
	<dependency>
		<groupId>org.springframework.cloudgroupId>
		<artifactId>spring-cloud-starter-consul-discoveryartifactId>
	dependency>
	<dependency>
		<groupId>org.springframework.cloudgroupId>
		<artifactId>spring-cloud-starter-bootstrapartifactId>
		<version>3.1.1version>
	dependency>
	<dependency>
		<groupId>org.springframework.bootgroupId>
		<artifactId>spring-boot-starter-actuatorartifactId>
	dependency>
	<dependency>
		<groupId>io.miniogroupId>
		<artifactId>minioartifactId>
		<version>8.2.1version>
	dependency>
dependencies>

二、在bootstrap.yml中配置

spring:
  application:
    name: minio-demo
  cloud:
    consul:
      config:
        format: yaml

三、在consul中配置

server:
  port: 8082
spring:
  application:
    name: minio-demo
  servlet:
    multipart:
      max-file-size: 1024MB
      max-request-size: 1024MB
obs:
  endpoint: http://127.0.0.1:9000
  accessKey: minioadmin
  secretKey: minioadmin
  bucketName: ${spring.application.name}

四、自定义配置类

package org.example.config;

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

@Configuration
public class MinioConfig {

    @Value("${obs.endpoint}")
    private String endpoint;

    @Value("${obs.accessKey}")
    private String accessKey;

    @Value("${obs.secretKey}")
    private String secretKey;

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

五、minio工具类

package org.example.util;

import io.micrometer.core.instrument.util.StringUtils;
import io.minio.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

@Component
public class MinioUtil {

    private final Logger log = LoggerFactory.getLogger(MinioUtil.class);

    @Value("${obs.bucketName}")
    private String bucketName;

    private final MinioClient minioClient;

    public MinioUtil(MinioClient minioClient) {
        this.minioClient = minioClient;
    }

    /**
     * 检查存储桶是否存在
     *
     * @param bucketName 存储桶名
     * @return 返回值
     */
    public boolean bucketExists(String bucketName) {
        boolean flag = false;
        try {
            flag = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (flag) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return false;
    }

    /**
     * 获取文件流
     *
     * @param fileName   文件名
     * @param bucketName 存储桶名
     * @return 返回值
     */
    public InputStream getFileInputStream(String fileName, String bucketName) {
        try {
            return minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(fileName).build());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 创建存储桶
     *
     * @param bucketName 存储桶名
     */
    public void createBucketName(String bucketName) {
        try {
            if (StringUtils.isBlank(bucketName)) {
                return;
            }
            boolean isExist = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (isExist) {
                log.info("Bucket [] already exists.", bucketName);
            } else {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
    }

    /**
     * 下载文件
     *
     * @param bucketName   存储桶名
     * @param originalName 文件名
     * @param response     响应
     * @return 返回结果
     */
    public InputStream downloadFile(String bucketName, String originalName, HttpServletResponse response) {
        try {
            InputStream file = minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).build());
            String filename = new String(originalName.getBytes("ISO8859-1"), StandardCharsets.UTF_8);
            if (StringUtils.isNotBlank(originalName)) {
                filename = originalName;
            }
            response.setHeader("Content-Disposition", "attachment;filename=" + filename);
            ServletOutputStream servletOutputStream = response.getOutputStream();
            int len;
            byte[] buffer = new byte[1024];
            while ((len = file.read(buffer)) > 0) {
                servletOutputStream.write(buffer, 0, len);
            }
            servletOutputStream.flush();
            file.close();
            servletOutputStream.close();
            return file;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 删除存储桶
     *
     * @param bucketName 存储桶名
     */
    public void deleteBucketName(String bucketName) {
        try {
            if (StringUtils.isBlank(bucketName)) {
                return;
            }
            boolean isExists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (isExists) {
                minioClient.removeBucket(RemoveBucketArgs.builder().bucket(bucketName).build());
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
    }

    /**
     * 删除存储桶下的所有文件
     *
     * @param bucketName 存储桶名
     */
    public void deleteBucketFile(String bucketName) {
        try {
            if (StringUtils.isBlank(bucketName)) {
                return;
            }
            boolean isExists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (isExists) {
                minioClient.deleteBucketEncryption(DeleteBucketEncryptionArgs.builder().bucket(bucketName).build());
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
    }

    /**
     * 根据文件路径得到预览文件绝对地址
     *
     * @param bucketName 存储桶名
     * @param fileName   文件名
     * @return 返回结果
     */
    public String getPreviewFileUrl(String bucketName, String fileName) {
        try {
            return minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder().bucket(bucketName).object(fileName).build());
        } catch (Exception e) {
            e.printStackTrace();
            return " ";
        }
    }

    /**
     * 上传文件
     *
     * @param file 文件
     */
    public void uploadFile(MultipartFile file) {
        try {
        	boolean bucketExists = bucketExists(bucketName);
            if(!bucketExists){
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            }
            String objectName = file.getOriginalFilename();
            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(bucketName)
                    .object(objectName)
                    .stream(file.getInputStream(), file.getInputStream().available(), -1)
                    .build());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

你可能感兴趣的:(微服务学习,spring,boot,后端,java)