java

Java 与 MinIO,实现文件服务调用

2023-07-09  本文已影响0人  林间树洞

1.MinIO相关配置

案例是在Docker的基础上运行MinIo

1.1.docker配置MinIO

拉取minio的镜像

 docker pull quay.io/minio/minio

创建文件保存的存储目录

mkdir /data/minio/data

运行minio的镜像,需要注意配置信息的填写

docker run -itd 
-p 9010:9000 
-p 9090:9090 
--name minio 
-d --restart=always 
-v /data/minio/data:/data 
-e "MINIO_ROOT_USER=`你的账号`" 
-e "MINIO_ROOT_PASSWORD=`你的密码`" 
quay.io/minio/minio server /data 
--console-address ":9090"  

1.2 创建minio相关配置需要登录其网页http://ip:9090

输入设置的你的账号你的密码就能登录了

image.png

创建Bucket存储桶

image.png
image.png

修改Bucket存储桶的配置

要让其他应用通过永久有效的URL访问图片,需要修改存储桶配置。否则,不能直接通过URL路径访问图片,而且提供的路径有时间限制,过一段时间就无法访问。

image.png
image.png

创建Access Keys,

image.png
image.png

2.SpringBoot 使用 MinIO的相关配置和代码

pom.xml引入依赖

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

yml配置

minio:
  endpoint: http://ip:9010  #ip是minio的网络地址
  accessKey: 'jQJgOx2sIuurNIGP'  #自己设置的key
  secretKey: '4geQyd6DaYrIN80r4BfqVLwwLJeT6DuH'
  bucketName: test  # 登陆minio创建的储存桶名字

创建文件对象ObjectItem

package com.xxx.common;

import lombok.Data;

@Data
public class ObjectItem {
    private String objectName;

    private Long size;
}

创建MinIoUtils工具类

package com.xxx.util;

import com.alibaba.csp.sentinel.util.StringUtil;
import com.xxx.common.ObjectItem;
import io.minio.*;
import io.minio.http.Method;
import io.minio.messages.DeleteError;
import io.minio.messages.DeleteObject;
import io.minio.messages.Item;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class MinIoUtils {

    @Autowired
    private MinioClient minioClient;

    @Value("${minio.bucketName}")
    private String bucketName;
    /**
     * description: 判断bucket是否存在,不存在则创建
     *
     * @return: void
     */
    public boolean existBucket(String name) {
        boolean exists;
        try {
            exists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(name).build());
            if (!exists) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(name).build());
                exists = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            exists = false;
        }
        return exists;
    }

    /**
     * 创建存储bucket
     *
     * @param bucketName 存储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
     *
     * @param bucketName 存储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;
    }

    /**
     * description: 上传文件
     *
     * @param file
     * @return: java.lang.String
     */
    public String upload(MultipartFile file, String fileName, String bucketNameStr) {
        InputStream in = null;
        try {
            if (StringUtil.isEmpty(bucketNameStr)) {
                bucketNameStr = bucketName;
            }
            in = file.getInputStream();
            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(bucketNameStr)
                    .object(fileName)
                    .stream(in, in.available(), -1)
                    .contentType(file.getContentType())
                    .build()
            );
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return bucketNameStr + "/" + fileName;
    }

    /**
     * description: 下载文件
     *
     * @param fileName
     * @return: org.springframework.http.ResponseEntity<byte [ ]>
     */
    public ResponseEntity<byte[]> download(String fileName) {
        ResponseEntity<byte[]> responseEntity = null;
        InputStream in = null;
        ByteArrayOutputStream out = null;
        try {
            in = minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(fileName).build());
            out = new ByteArrayOutputStream();
            IOUtils.copy(in, out);
            //封装返回值
            byte[] bytes = out.toByteArray();
            HttpHeaders headers = new HttpHeaders();
            try {
                headers.add("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            headers.setContentLength(bytes.length);
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setAccessControlExposeHeaders(Arrays.asList("*"));
            responseEntity = new ResponseEntity<byte[]>(bytes, headers, HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return responseEntity;
    }

    /**
     * 查看文件对象
     *
     * @param bucketName 存储bucket名称
     * @return 存储bucket内文件对象信息
     */
    public List<ObjectItem> listObjects(String bucketName) {
        Iterable<Result<Item>> results = minioClient.listObjects(
                ListObjectsArgs.builder().bucket(bucketName).build());
        List<ObjectItem> objectItems = new ArrayList<>();
        try {
            for (Result<Item> result : results) {
                Item item = result.get();
                ObjectItem objectItem = new ObjectItem();
                objectItem.setObjectName(item.objectName());
                objectItem.setSize(item.size());
                objectItems.add(objectItem);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return objectItems;
    }

    /**
     * 批量删除文件对象
     *
     * @param bucketName 存储bucket名称
     * @param objects    对象名称集合
     */
    public Iterable<Result<DeleteError>> removeObjects(String bucketName, List<String> objects) {
        List<DeleteObject> dos = objects.stream().map(e -> new DeleteObject(e)).collect(Collectors.toList());
        Iterable<Result<DeleteError>> results = minioClient.removeObjects(RemoveObjectsArgs.builder().bucket(bucketName).objects(dos).build());
        return results;
    }

    /**
     * 根据文件名和桶获取文件路径
     *
     * @param bucketName 存储bucket名称
     */
    public String getFileUrl(String bucketName, String objectFile) {
        try {
            if(StringUtil.isEmpty(bucketName)){
                bucketName = this.bucketName;
            }
            return minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder()
                    .method(Method.GET)
                    .bucket(bucketName)
                    .object(objectFile)
                    .build()
            );
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

创建MinIO的Controller

package com.xxx.modules.controller;

import com.alibaba.fastjson.JSONObject;
import com.leanmed.common.ObjectItem;
import com.leanmed.util.MinIoUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * @author xxx
 * @version 1.0
 * @className MinioController
 * @description
 * @create 2022/5/28 16:33
 */
@RestController
@RequestMapping("/minio")
public class MinioController {


    @Autowired
    private MinIoUtils minioUtils;
    @Value("${minio.endpoint}")
    private String address;
    @Value("${minio.bucketName}")
    private String bucketName;

    @PostMapping("/upload")
    public Object upload(@RequestParam(value = "file") MultipartFile file, @RequestParam("bucketName") String bucketName) {
        return address + "/"  + minioUtils.upload(file, file.getOriginalFilename(), bucketName);
    }

    @PostMapping("/getListByBucket")
    public List<ObjectItem> getListByBucket() {
        List<ObjectItem> list = minioUtils.listObjects(bucketName);
        return list;
    }

    @PostMapping("/existBucket")
    public boolean existBucket(@RequestBody JSONObject jsonObject) {
        return minioUtils.existBucket(jsonObject.getString("name"));
    }

    @PostMapping("/makeBucket")
    public boolean makeBucket(@RequestBody JSONObject jsonObject) {
        return minioUtils.makeBucket(jsonObject.getString("name"));
    }

    @PostMapping("/removeBucket")
    public boolean removeBucket(@RequestBody JSONObject jsonObject) {
        return minioUtils.removeBucket(jsonObject.getString("name"));
    }

    @PostMapping("/getFileUrl")
    public String  getFileUrl(@RequestBody JSONObject jsonObject) {
        return minioUtils.getFileUrl(jsonObject.getString("bucketName"),jsonObject.getString("fileName"));
    }

    @GetMapping("/loadFile")
    @ResponseBody
    public ResponseEntity<?> loadFile(@RequestParam("filePath") String filePath) {
        return minioUtils.download(filePath);
    }
}


上一篇下一篇

猜你喜欢

热点阅读