springboot整合minio

news2024/7/2 3:25:11

minio是对象存储服务。它基于Apache License 开源协议,兼容Amazon S3云存储接口。适合存储非结构化数据,如图片,音频,视频,日志等。对象文件最大可以达到5TB。

优点有高性能,可扩展,操作简单,有图形化操作界面,读写性能优异等。

minio的安装也很简单,有兴趣的可以去 https://min.io 官网看看。Mac安装详解如:

 minio服务端和客户端的安装直接用命令行安装即可。

接下来我们直接展示整合代码,首先是pom依赖文件(官网有):

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

application.yml文件:

minio:
  url: 129.0.0.1:9000 #换成自己的minio服务端地址
  access-key: minioadmin
  secret-key: minioadmin
  bucket-name: ding_server

然后是minio配置文件:

@Data
@Configuration
@Component
@PropertySource(value = {"classpath:application.yml"},
        ignoreResourceNotFound = false, encoding = "UTF-8", name = "authorSetting.properties")
@ConfigurationProperties(value = "minio")
public class MinioProperties {

    @Value("${minio.url}")
    private String url;
    @Value("${minio.access-key}")
    private String accessKey;
    @Value("${minio.secret-key}")
    private String secretKey;
    @Value("${minio.bucket-name}")
    private String bucketName;

}
MinioTemplate文件:
import io.minio.MinioClient;
import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.xmlpull.v1.XmlPullParserException;

import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

@Component
@Configuration
@EnableConfigurationProperties(MinioProperties.class)
public class MinioTemplate {
    @Autowired
    private MinioProperties minioProperties;

    private MinioClient minioClient;

    public MinioTemplate() {}

    public MinioClient getMinioClient() {
        if (minioClient == null) {
            try {
                return new MinioClient(minioProperties.getUrl(), minioProperties.getAccessKey(), minioProperties.getSecretKey());
            } catch (InvalidEndpointException e) {
                e.printStackTrace();
            } catch (InvalidPortException e) {
                e.printStackTrace();
            }
        }
        return minioClient;
    }

    public void createBucket(String bucketName) throws IOException, InvalidKeyException, NoSuchAlgorithmException, InsufficientDataException, InvalidResponseException, InternalException, NoResponseException, InvalidBucketNameException, XmlPullParserException, ErrorResponseException, RegionConflictException {
        MinioClient minioClient = getMinioClient();
        if (!minioClient.bucketExists(bucketName)) {
            minioClient.makeBucket(bucketName);
        }
    }

    /**
     * 获取文件外链
     * @param bucketName bucket 名称
     * @param objectName 文件名称
     * @param expires   过期时间 <=7
     * @return
     */
    public String getObjectURL(String bucketName,String objectName,int expires) throws IOException, InvalidKeyException, NoSuchAlgorithmException, InsufficientDataException, InvalidExpiresRangeException, InvalidResponseException, InternalException, NoResponseException, InvalidBucketNameException, XmlPullParserException, ErrorResponseException {
        return getMinioClient().presignedGetObject(bucketName, objectName, expires);
    }

    /**
     * 获取文件
     * @param bucketName
     * @param objectName
     * @return
     */
    public InputStream getObject(String bucketName,String objectName) throws IOException, InvalidKeyException, NoSuchAlgorithmException, InsufficientDataException, InvalidArgumentException, InvalidResponseException, InternalException, NoResponseException, InvalidBucketNameException, XmlPullParserException, ErrorResponseException {
        return getMinioClient().getObject(bucketName, objectName);
    }

    /**
     * 上传文件
     * @param bucketName
     * @param objectName
     * @param stream
     */
    public void putObject(String bucketName, String objectName, InputStream stream) throws IOException, XmlPullParserException, NoSuchAlgorithmException, RegionConflictException, InvalidKeyException, InvalidResponseException, ErrorResponseException, NoResponseException, InvalidBucketNameException, InsufficientDataException, InternalException, InvalidArgumentException {
        createBucket(bucketName);
        getMinioClient().putObject(bucketName,objectName,stream,stream.available(),"application/octet-stream");
    }

    public void putObject(String bucketName, String objectName, InputStream stream, int size, String contextType) throws IOException, XmlPullParserException, NoSuchAlgorithmException, RegionConflictException, InvalidKeyException, InvalidResponseException, ErrorResponseException, NoResponseException, InvalidBucketNameException, InsufficientDataException, InternalException, InvalidArgumentException {
        createBucket(bucketName);
        getMinioClient().putObject(bucketName,objectName,stream,size,contextType);
    }

    /**
     * 删除文件
     * @param bucketName
     * @param objectName
     */
    public void removeObject(String bucketName, String objectName) throws IOException, InvalidKeyException, NoSuchAlgorithmException, InsufficientDataException, InvalidArgumentException, InvalidResponseException, InternalException, NoResponseException, InvalidBucketNameException, XmlPullParserException, ErrorResponseException {
        getMinioClient().removeObject(bucketName,objectName);
    }

}

最后是工具类(bucketName可以外部传入,也可以写个定植,根据业务需求选择):

import com.haileer.dd.dingdingserver.config.MinioTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

@Service
public class MinioStorageService {

    @Autowired
    private MinioTemplate minioTemplate;

    private String bucketName = "dingding";

    /**
     * 获取文件外链
     *
     * @param objectName 文件名称
     * @param expires    过期时间 <=7
     * @return url
     * @throws Exception https://docs.minio.io/cn/java-client-api-reference.html#getObject
     */
    public String getObjectURL(String objectName, int expires) {
        try {
            return minioTemplate.getObjectURL(bucketName, objectName, expires);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public String uploadFile(byte[] data, String filePath) {
        InputStream inputStream = new ByteArrayInputStream(data);
        String path = null;
        try {
            minioTemplate.putObject(bucketName, filePath, inputStream);
            path = filePath;
        } catch (Exception e) {

        }
        return path;
    }

    public String uploadFile(String bucketName, byte[] data, String filePath) {
        InputStream inputStream = new ByteArrayInputStream(data);
        String path = null;
        try {
            minioTemplate.putObject(bucketName, filePath, inputStream);
            path = filePath;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return path;
    }


    public String uploadFile(InputStream inputStream, String fileName, String contentType) {
        String path = null;
        try {
            minioTemplate.putObject(bucketName, fileName, inputStream, inputStream.available(), contentType);
            path = fileName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return path;
    }


    public String uploadFile(String bucketName, InputStream inputStream, String fileName, String contentType) {
        String path = null;
        try {
            minioTemplate.putObject(bucketName, fileName, inputStream, inputStream.available(), contentType);
            path = fileName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return path;
    }

    public InputStream downloadFile(String filePath) {
        InputStream inputStream = null;
        try {
            inputStream = minioTemplate.getObject(bucketName, filePath);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return inputStream;
    }

    public void removeFile(String filePath){
        try{
            minioTemplate.removeObject(bucketName,filePath);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

}

我们来看看使用:

在swagger上测试:

 再去查看minio服务上:

 上传成功啦!下载图片我选择的方式是接口方式:

    @GetMapping("download")
    @ApiOperation(value = "下载文件")
    public Results download(HttpServletResponse response,@RequestParam("filePath")String filePath)  {
        if(!StringUtils.isEmpty(filePath)){
            InputStream inputStream = minioStorageService.downloadFile(filePath);
            if (inputStream != null) {
                response.setContentType("application/force-download");// 设置强制下载不打开
                response.setHeader("Content-Disposition", "attachment;filename=" + filePath);
                response.setCharacterEncoding("UTF-8");
                byte[] buffer = new byte[1024];
                BufferedInputStream bis = null;
                try {
                    bis = new BufferedInputStream(inputStream);
                    ServletOutputStream outputStream = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        outputStream.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                    return null;
                } catch (Exception e) {
                    e.printStackTrace();
                }finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (inputStream != null) {
                        try {
                            inputStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }

            }
        }
        return new Results(500, "下载失败");
    }

然后用访问接口的方式下载图片就可以了!http://127.0.0.1:8080/file/download?filePath= 即可。

以上就是springboot整合minio服务存储对象以及上传下载文件的全部代码啦。下次见!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/47598.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

招标网站信息爬取

目标网站 某采购与招标网  代码链接code-repo 准备工作 参考博客[1]&#xff0c;使用谷歌浏览器的开发者工具&#xff0c;提取http的表单信息。  http post 中的表单信息&#xff0c;需要含有_qt信息。网站使用_qt做反爬虫措施。_qt由服务器返回&#xff0c;在不同的会话中…

第五站:操作符(终幕)(一些经典的题目)

目录 一、分析下面的代码 二、统计二进制中1的个数 解一&#xff1a;&#xff08;求出每一个二进制位&#xff0c;来统计1的个数&#xff09; 解二&#xff1a;&#xff08;利用左我们移或右移操作符和按位与&#xff09; 解三&#xff1a;&#xff08;效率最高的解法&…

Java中的集合框架

目录 集合体系 Collection - List接口实现类 Collection - List接口对象的遍历 Collection - List - ArrayList Collection - List - Vector Collection - List - LinkedList Collection - Set接口实现类 Collection - Set接口的遍历 Collection - Set - HashSet Has…

哈夫曼压缩算法-Python实现

前面上传了A*算法的实现&#xff0c;就顺便把一起写的哈夫曼压缩也上传了吧 本文主要提供了Python版本的哈夫曼压缩算法实现&#xff0c;并在此基础上提供了命令行和基于Qt的GUI用户界面&#xff08;User Interface&#xff09; 哈夫曼&#xff08;Huffman Encoding&#xff09…

HTTP 协议内容的介绍与应用

HTTP简介 HTTP 超文本传输协议(Hyper Text Transfer Protocol)是一个应用层的协议&#xff0c;使用相当广泛&#xff0c;比如我们常说浏览器敲入网址打开网页&#xff0c;浏览器跟后台服务器之间就用的是HTTP&#xff0c;并且也常用于后端各个微服务之间的数据请求和通信。是我…

【学习笔记62】判断数据类型的方法

1. typeof&#xff1a;判断基本数据类型 console.log(typeof(123));console.log(typeof(123));console.log(typeof(true));console.log(typeof(undefined));console.log(typeof([1, 2, 3]));console.log(typeof({a:1}));2. constructor 可以判断当前数据的构造函数是谁 const …

Node.js 入门教程 51 Node.js Buffer

Node.js 入门教程 Node.js官方入门教程 Node.js中文网 本文仅用于学习记录&#xff0c;不存在任何商业用途&#xff0c;如侵删 文章目录Node.js 入门教程51 Node.js Buffer51.1 什么是 buffer&#xff1f;51.2 为什么需要 buffer&#xff1f;51.3 如何创建buffer51.4 使用 buff…

KVM虚拟化部署

一、 安装配置KVM 相关软件 检查本机CPU是否支持虚拟化 intel: 最新linux内核的Intel处理器(含VT虚拟化技术) vmx nx lm AMD: 含SVM安全虚拟机技术的AMD处理器, 也叫AMD-V svm nx lm 可以使用如下命令检查&#xff1a; [rootzutuanxue ~]# egrep "(vmx|svm)" /p…

进销存系统和ERP系统怎么选?有什么区别?

首要任务就是把各种专属术语名词的含义搞清楚&#xff0c;否则就要饭碗不保了&#xff0c;现在把自己学习到的知识分享给大家&#xff0c;希望能够帮助到有需要的人&#xff1a;进销存和ERP有什么不同&#xff1f;进销存属于ERP吗&#xff1f;一起来了解一下吧。 一、概念定义…

药师帮再冲刺上市:研发远低于营销,债务高企,张步镇为董事长

11月28日&#xff0c;药师帮股份有限公司&#xff08;下称“药师帮”&#xff09;再次在港交所递交招股书&#xff0c;高盛和中金公司为联席保荐人。据贝多财经了解&#xff0c;这是药师帮第二次递交上市申请&#xff0c;此前曾于2022年5月24日递表。 据了解&#xff0c;药师帮…

ImageEn FMX内置图像效果对话框

ImageEn FMX内置图像效果对话框 我们现在发布了ImageEn/FireMonkey的测试版。目前&#xff0c;仅支持Windows目标&#xff0c;计划使用其他平台。 ImageEn FMX功能强大&#xff1a; 任何对话框 ImageEn打开/保存对话框 内置图像效果对话框(TImageEnProc.DoPreviews) 内置图像I/…

基于PHP+MySQL邮件管理系统的设计与开发

如今,随着社交软件的兴起,邮箱的地位被撼动,但是邮箱的重要性始终不能被忽视。人们在社交软件不发达的那个年代,距离很近的人的交流方式是面对面的,而距离很远的人则是通过书信的形式进行交流,但是随着社交软件的兴起,有各种各样的交流方式,但是邮箱在企业交流、生意场合、校园…

《深入浅出WPF》学习笔记

目录书山有路勤为径&#xff0c;学海无涯苦作舟1.Binding1.Binding的源和路径1.1 把控件作为Binding源与Binding标记扩展1.2 控制Binding的方向及数据更新1.3 没有“Path”的Binding1.4通过Binding的RelativeSource属性指定Source1.5把ObjectDataProvider对象指定为Source书山有…

Python爬虫学了几个月却不敢接单?过来人的经验总结收好!

前几天有刷到一个提问&#xff1a;爬虫学了几个月了却还是不敢上手去接单&#xff0c;爬虫接单靠不靠谱&#xff1f;有些新手心里会犯嘀咕&#xff0c;怕不小心就踩了红线。作为过来人也接过不少单&#xff0c;来浅聊一下我的经验。 这篇所说的经验总结可能更适合爬虫新手&…

SMARTBI权限管理

数据集是专门针对数据可视化和分析要求构建的自助数据模型。 文章目录前言一、用户管理二、数据集权限管理三、报表权限管理总结前言 分享SMARTBI权限管理的操作&#xff0c;供各位小伙伴参考。SMERTBI的权限可以细分到将某个表中某个字段的某个值授权给某个用户&#xff0c;比…

Oracle 创建PDB的几种常用方法

PDB是运行在PDB上的一个数据库&#xff0c;各个PDB是独立运行的。在CDB中创建、删除、迁移PDB是非常方便的事情。不会对其它CDB和PDB产生任何影响。 CREATE PDB METHOD 创建PDB的简要说明 利用Seed(种子)模板来创建 默认方法&#xff0c;使用PDB Seed或应用程序的模板文件夹创…

完结篇:操作符详解(2)

目录 一、单目操作符 1、! 逻辑反操作 补充&#xff1a;布尔类型 2、& 取地址操作符 3、* 间接访问操作符&#xff08;解引用操作符&#xff09; 4、sizeof 计算操作数的类型长度 5、~ 操作符 操作符的结合使用 6、操作符&#xff08;前置/后置&#xff09; 7、--操作符&…

【毕业设计】19-基于单片机的物件计数控制系统设计(原理图工程+源代码工程+仿真工程+答辩论文)

typora-root-url: ./ 【毕业设计】19-基于单片机的物件计数控制系统设计&#xff08;原理图工程源代码工程仿真工程答辩论文&#xff09; 文章目录typora-root-url: ./【毕业设计】19-基于单片机的物件计数控制系统设计&#xff08;原理图工程源代码工程仿真工程答辩论文&…

【深度学习】pix2pix GAN理论及代码实现与理解

灵感&#xff1a;最近也是在看关于GAN方面的代码&#xff0c;也是看到了很多篇博客&#xff0c;都写的挺好的&#xff0c;让我醍醐灌顶&#xff0c;理解了GAN的原理以及代码实现。所以写一下来记载一下&#xff0c;最后有其他好文章的链接。 灵感来源&#xff1a;pix2pixGAN理…

干货 | 提前在开发阶段暴露代码问题,携程Alchemy代码质量平台

作者简介Lyan&#xff0c;携程资深后端开发工程师&#xff0c;负责自动化测试框架及平台类工具开发&#xff0c;关注Devops、研发效能领域。一、背景随着敏捷开发&#xff0c;DevOps开发模式的流行&#xff0c;代码质量分析作为研发质量保证体系的重要组成部分&#xff0c;不仅…