java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > springboot集成Minio文件服务器

springboot如何集成Minio文件服务器

作者:Mr-Wanter

这篇文章主要介绍了springboot如何集成Minio文件服务器问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教

springboot集成Minio文件服务器

一、添加依赖

dependency>
    <groupId>io.minio</groupId>
    <artifactId>minio</artifactId>
    <version>7.1.0</version>
</dependency>

二、集成springboot并提供工具类

package com.gsafety.bg.gsdss.file.manage.service.util;

import com.gsafety.bg.gsdss.file.config.properties.S3OssProperties;
import com.gsafety.bg.gsdss.web.agile.BizPreconditions;
import io.minio.*;
import io.minio.messages.Bucket;
import io.minio.messages.Item;
import lombok.SneakyThrows;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.Assert;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;

/**
 * Minio 基础操作类
 *
 * @author: zhanghuaiyu
 * @since 2021-01-22 16:27
 */
@Configuration
public class MinioTemplate implements InitializingBean {
    @Resource
    private S3OssProperties properties;
    
    private MinioClient minioClient;
    
    @Override
    public void afterPropertiesSet() {
        Assert.hasText(properties.getUrl(), "Minio url 为空");
        Assert.hasText(properties.getAccessKey(), "Minio accessKey为空");
        Assert.hasText(properties.getSecretKey(), "Minio secretKey为空");
        this.minioClient = new MinioClient(properties.getUrl(), properties.getAccessKey(), properties.getSecretKey());
    }
    
    /**
     * 创建bucket
     * setBucketPolicy 设置权限才可以预览
     *
     * @param bucketName bucket名称
     */
    @SneakyThrows
    public Boolean createBucket(String bucketName) {
        if (!bucketExists(bucketName)) {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            StringBuilder builder = new StringBuilder();
            builder.append("{\n");
            builder.append("    \"Statement\": [\n");
            builder.append("        {\n");
            builder.append("            \"Action\": [\n");
            builder.append("                \"s3:GetBucketLocation\",\n");
            builder.append("                \"s3:ListBucket\"\n");
            builder.append("            ],\n");
            builder.append("            \"Effect\": \"Allow\",\n");
            builder.append("            \"Principal\": \"*\",\n");
            builder.append("            \"Resource\": \"arn:aws:s3:::my-bucketname\"\n");
            builder.append("        },\n");
            builder.append("        {\n");
            builder.append("            \"Action\": \"s3:GetObject\",\n");
            builder.append("            \"Effect\": \"Allow\",\n");
            builder.append("            \"Principal\": \"*\",\n");
            builder.append("            \"Resource\": \"arn:aws:s3:::my-bucketname/*.*\"\n");
            builder.append("        }\n");
            builder.append("    ],\n");
            builder.append("    \"Version\": \"2012-10-17\"\n");
            builder.append("}\n");
            minioClient.setBucketPolicy(SetBucketPolicyArgs.builder().bucket(bucketName).config(builder.toString().replace("my-bucketname", bucketName)).build());
            return true;
        } else {
            return false;
        }
    }
    
    /**
     * 获取全部bucket
     * <p>
     * https://docs.minio.io/cn/java-client-api-reference.html#listBuckets
     */
    @SneakyThrows
    public List<Bucket> getAllBuckets() {
        return minioClient.listBuckets();
    }
    
    /**
     * 根据bucketName获取信息
     *
     * @param bucketName bucket名称
     */
    @SneakyThrows
    public Optional<Bucket> getBucket(String bucketName) {
        return minioClient.listBuckets().stream().filter(b -> b.name().equals(bucketName)).findFirst();
    }
    
    /**
     * 根据bucketName删除信息
     *
     * @param bucketName bucket名称
     */
    @SneakyThrows
    public void removeBucket(String bucketName) {
        minioClient.removeBucket(RemoveBucketArgs.builder().bucket(bucketName).build());
    }
    
    /**
     * 根据文件前置查询文件
     *
     * @param bucketName bucket名称
     * @param prefix     前缀
     * @param recursive  是否递归查询
     * @return MinioItem 列表
     */
    @SneakyThrows
    public List getAllObjectsByPrefix(String bucketName, String prefix, boolean recursive) {
        List<Item> list = new ArrayList<>();
        Iterable<Result<Item>> objectsIterator = minioClient.listObjects(bucketName, prefix, recursive);
        if (objectsIterator != null) {
            Iterator<Result<Item>> iterator = objectsIterator.iterator();
            if (iterator != null) {
                while (iterator.hasNext()) {
                    Result<Item> result = iterator.next();
                    Item item = result.get();
                    list.add(item);
                }
            }
        }
        
        return list;
    }
    
    /**
     * 获取文件外链
     *
     * @param bucketName bucket名称
     * @param objectName 文件名称
     * @param expires    过期时间 <=7
     * @return url
     */
    @SneakyThrows
    public String getObjectUrl(String bucketName, String objectName, Integer expires) {
        return minioClient.presignedGetObject(bucketName, objectName, expires);
    }
    
    /**
     * 获取文件路径
     *
     * @param bucketName
     * @param fileName
     * @return
     */
    @SneakyThrows
    public String getObjectUrl(String bucketName, String fileName) {
        return minioClient.getObjectUrl(bucketName, fileName);
    }
    
    /**
     * 获取文件
     *
     * @param bucketName bucket名称
     * @param objectName 文件名称
     * @return 二进制流
     */
    @SneakyThrows
    public InputStream getObject(String bucketName, String objectName) {
        return minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(objectName).build());
    }
    
    /**
     * 获取文件
     *
     * @param bucketName
     * @param objectName
     * @return
     */
    @SneakyThrows
    public ObjectStat statObject(String bucketName, String objectName) {
        return minioClient.statObject(StatObjectArgs.builder().bucket(bucketName).object(objectName).build());
    }
    
    /**
     * 上传文件
     *
     * @param bucketName bucket名称
     * @param objectName 文件名称
     * @throws Exception https://docs.minio.io/cn/java-client-api-reference.html#putObject
     */
    public String putObject(String bucketName, String objectName, MultipartFile file) throws Exception {
        if (!this.bucketExists(bucketName)) {
            this.createBucket(bucketName);
        }
        minioClient.putObject(PutObjectArgs.builder().bucket(bucketName).object(objectName).stream(file.getInputStream(), file.getSize(), PutObjectArgs.MIN_MULTIPART_SIZE).contentType(file.getContentType()).build());
        return bucketName;
    }
    
    /**
     * 上传文件
     *
     * @param bucketName bucket名称
     * @param objectName 文件名称
     * @param stream     文件流
     * @param size       大小
     * @throws Exception https://docs.minio.io/cn/java-client-api-reference.html#putObject
     */
    public void putObject(String bucketName, String objectName, InputStream stream, long size) throws Exception {
        
        minioClient.putObject(bucketName, objectName, stream, new PutObjectOptions(stream.available(), -1));
    }
    
    /**
     * 获取文件信息, 如果抛出异常则说明文件不存在
     *
     * @param bucketName bucket名称
     * @param objectName 文件名称
     * @throws Exception https://docs.minio.io/cn/java-client-api-reference.html#statObject
     */
    public ObjectStat getObjectInfo(String bucketName, String objectName) throws Exception {
        
        return minioClient.statObject(StatObjectArgs.builder().bucket(bucketName).object(objectName).build());
    }
    
    /**
     * 删除文件
     *
     * @param bucketName bucket名称
     * @param objectName 文件名称
     * @throws Exception https://docs.minio.io/cn/java-client-api-reference.html#removeObject
     */
    public void removeObject(String bucketName, String objectName) throws Exception {
        minioClient.removeObject(RemoveObjectArgs.builder().bucket(bucketName).object(objectName).build());
    }
    
    /**
     * 批量删除文件夹内所有文件
     *
     * @param bucketName bucket名称
     * @param objectName 文件名称
     * @throws Exception https://docs.minio.io/cn/java-client-api-reference.html#removeObject
     */
    public void removeObjects(String bucketName, String objectName) throws Exception {
        List<Item> list = getAllObjectsByPrefix(bucketName, objectName, false);
        for (Item item : list) {
            removeObject(bucketName, item.objectName());
        }
    }
    
    @SneakyThrows
    public boolean bucketExists(String bucketName) {
        return minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
    }
    
    /**
     * 文件下载
     *
     * @param response
     * @param bucket
     * @param objectName
     * @param outName
     * @throws Exception
     */
    public void download(HttpServletResponse response, String bucket, String objectName, String outName) throws Exception {
        BizPreconditions.checkArgumentNoStack(this.bucketExists(bucket), "目录" + bucket + "不存在!");
        ObjectStat stat = this.statObject(bucket, objectName);
        response.setContentType(stat.contentType());
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(outName, "UTF-8"));
        response.setHeader("FileName", URLEncoder.encode(outName, "UTF-8"));
        InputStream in = this.getObject(bucket, objectName);
        IOUtils.copy(in, response.getOutputStream());
        in.close();
    }
    
    /**
     * 合并分片文件到指定目录
     *
     * @param bucket
     * @param fileName
     * @param sources
     * @return
     * @throws Exception
     */
    public ObjectWriteResponse composeObject(String bucket, String fileName, List<ComposeSource> sources) throws Exception {
        ObjectWriteResponse response = minioClient.composeObject(ComposeObjectArgs.builder()
                .bucket(bucket)
                .object(fileName)
                .sources(sources)
                .build());
        return response;
    }
}


三、配置信息

minio.url=http://172.20.0.252:8991
minio.accessKey=admin
minio.secretKey=admin123
minio.bucketName=data

四、crud 示例

import cn.com.result.JsonResult;
import cn.com.sys.exception.BusinessException;
import cn.com.util.MinioTemplate;
import io.minio.ObjectStat;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;

/**
 * minio上传,下载,删除接口
 */
@RestController
@RequestMapping("/minio")
public class MinioController {


    @Autowired
    private MinioTemplate minioTemplate;

    /**
     * 下载文件
     */
    @ApiOperation(value = "下载文件")
    @GetMapping(value = "/download")
    @SneakyThrows(Exception.class)
    public void download(@RequestParam("fileName") String fileName, HttpServletResponse response) {
        ObjectStat stat = minioTemplate.statObject("", fileName);
        response.setContentType(stat.contentType());
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        InputStream in = minioTemplate.getObject("", fileName);
        IOUtils.copy(in, response.getOutputStream());
        in.close();
    }

    /**
     * 上传文件
     * @param file
     * @return
     * @throws Exception Exception
     */
    @ApiOperation(value = "上传文件")
    @PostMapping(value = "/upload")
    @SneakyThrows(Exception.class)
    public JsonResult upload(@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            throw new BusinessException("上传文件不能为空");
        } else {
            // 得到文件流
            final InputStream is = file.getInputStream();
            // 文件名
            final String fileName = file.getOriginalFilename();
            // 把文件放到minio的boots桶里面
            minioTemplate.putObject("",fileName,is,-1);
            String objectUrl = minioTemplate.getObjectURL("",fileName);
            // 关闭输入流
            is.close();
            return JsonResult.ok(objectUrl);
        }
    }

    /**
     * 删除文件
     * @param fileName
     * @return JsonResult
     */
    @ApiOperation(value = "删除文件")
    @GetMapping(value = "/delete", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @SneakyThrows(Exception.class)
    public JsonResult delete(@RequestParam("fileName") String fileName) {
        minioTemplate.removeObject("",fileName);
        return JsonResult.ok("删除成功");
    }

}

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文