SpringBoot整合MinIO文件存储服务

发布于 2020-08-04  4022 次阅读


官方文档地址:http://docs.minio.org.cn/docs/master

注:服务安装这里有个坑,服务器是x86_64的,按照官网的一直说不支持二进制文件( -bash: ./minio: cannot execute binary file )后面从中国镜像站下载的LINUX-386版本的完美运行http://dl.minio.org.cn/server/minio/release/linux-386/?C=M&O=A

目前团队所有项目都是采用微服务模式,但是没有一个专门的文件服务,所有文件都是放在网关的目录中,存在很多安全隐患,比对过 fastdfs 后,决定使用 MinIO 来做文件存储服务,本文仅做一个快速入门的示例介绍。完整的文件存储服务可关注我的Gitee,所有代码均开源,地址:https://gitee.com/uxue/file-upload

Maven依赖

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

上传代码示例:

@PostMapping("upload")
    public ObjectWriteResponse testUploadFile(@RequestParam("file") MultipartFile file, @RequestParam(value = "serverName", required = false) String serverName) throws IOException, InvalidKeyException, InvalidResponseException, RegionConflictException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {
        ObjectWriteResponse objectWriteResponse = null;
        if (StringUtils.isNotEmpty(serverName)) {
            //TMinioServer minioServer = tMinioServerService.getMinioServerByName(serverName);
            //if (minioServer != null) {
            //构建minioClient
                MinioClient minioClient =
                        MinioClient.builder()
                                .endpoint("10.108.6.118", 9000, false) //secure 是否启用https
                                .credentials("CBXMIADY6YE4HLOV9XPC", "H560xCsyqthlz2UWMLRWUR2/EAyNRQ3o82qZArzi")
                                .build();
                //minioClient.makeBucket("test");
                InputStream inputStream = file.getInputStream();
                PutObjectArgs.Builder stream = PutObjectArgs.builder()
                        .contentType(file.getContentType())
                        //如果文件大小未知,则将-1传递给objectSize并传递有效的partSize。
                        //如果知道对象大小,则将-1传递给partSize进行自动检测;
                        .stream(inputStream,file.getSize(),-1)
                        .bucket("test")
                        .object("测试文件"); //服务器端存储的文件名
                objectWriteResponse = minioClient.putObject(stream.build());
            }
        //}
        return objectWriteResponse;
    }

官方文档应该是没有跟着版本发布一起更新,很多方法基本上废弃了,推荐还是看MinioClient中的可以用的方法,上面只是列举了其中的一种上传文件的方式。


个人博客,用于记录工作日常的问题。