springboot整合minio

这篇具有很好参考价值的文章主要介绍了springboot整合minio。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

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

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

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

springboot整合minio

 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();
        }
    }

}

我们来看看使用:

springboot整合minio

在swagger上测试:

springboot整合minio 再去查看minio服务上:

springboot整合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服务存储对象以及上传下载文件的全部代码啦。下次见!文章来源地址https://www.toymoban.com/news/detail-470765.html

到了这里,关于springboot整合minio的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 【微服务】springboot整合minio详解

    目录 一、前言 二、Minio 概述 2.1 Minio简介 2.1 Minio特点 三、Minio 环境搭建

    2024年02月04日
    浏览(30)
  • SpringBoot整合minio服务(超详细)

    创建一个名为public的存储桶(名字可自定义),上传文件。 通过 http://ip:9000/存储桶名/文件名 访问文件 若出现: 可以将存储桶的访问权限设置为public. 在application.yml文件中编写相关配置。 开发中上传接口用得较多,其他接口可自行测试。  # npm下载element-ui npm install element-

    2024年02月08日
    浏览(30)
  • minio开源的对象存储服务器安装及使用

    MinIO是一个开源的对象存储服务器,设计用于实现高性能、可扩展的云存储。它兼容Amazon S3云存储服务的API,因此可以与现有的S3兼容应用程序进行集成。 MinIO可以部署在本地服务器、私有云环境或公共云上,如AWS、Azure、Google Cloud等。它通过将数据分散在多个独立节点上实现

    2024年02月08日
    浏览(39)
  • ancos注册中心、网关和静态化freemarker、对象存储服务MinIO

    1、docker安装ancos Nacos 分布式注册中心 ①:docker拉取镜像 ②:创建容器 ③:访问地址: http://192.168.200.130:8848/nacos 2、 网关 2.1 pom.xml文件导入依赖 2.2 创建微服务(搜索微服务、登录微服务等) 启动类需要加上@EnableDiscoveryClient注解 bootstrap.xml 注意 :配置文件bootstrap.yml ,这里

    2024年02月15日
    浏览(29)
  • Docker部署MinIO对象存储服务器结合Cpolar实现远程访问

    🔥 博客主页 : 小羊失眠啦. 🎥 系列专栏 : 《C语言》 《数据结构》 《Linux》 《Cpolar》 ❤️ 感谢大家点赞👍收藏⭐评论✍️ 前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点击跳转到网站。 MinIO是一个开源的对象存储服务器

    2024年02月05日
    浏览(49)
  • SpringBoot整合阿里云OSS对象存储

    阿里云对象存储服务(Object Storage Service,简称OSS)为您提供基于网络的数据存取服务。使用OSS,您可以通过网络随时存储和调用包括文本、图片、音频和视频等在内的各种非结构化数据文件。 阿里云OSS将数据文件以对象(object)的形式上传到存储空间(bucket)中。 可以进行

    2024年02月06日
    浏览(40)
  • springboot快速整合腾讯云COS对象存储

    1、导入相关依赖 2、编写配置类,获取配置信息 创建配置类主要需要以下信息 腾讯云账号秘钥 和 密码秘钥: 用于创建COSClient链接对象,识别用户身份信息 存储桶区域 :需要设置客户端所属区域Region 存储桶名称 :创建请求时,需要告知上传到哪个存储桶下 存储桶访问路径

    2024年02月15日
    浏览(38)
  • Docker部署MinIO对象存储服务器结合内网穿透实现远程访问

    MinIO是一个开源的对象存储服务器,可以在各种环境中运行,例如本地、Docker容器、Kubernetes集群等。它兼容Amazon S3 API,因此可以与现有的S3工具和库无缝集成。MinIO的设计目标是高性能、高可用性和可扩展性。它可以在分布式模式下运行,以满足不同规模的存储需求。 MinIO是

    2024年02月04日
    浏览(39)
  • Docker本地部署MinIO对象存储服务器结合Cpolar内网穿透实现远程访问

    MinIO是一个开源的对象存储服务器,可以在各种环境中运行,例如本地、Docker容器、Kubernetes集群等。它兼容Amazon S3 API,因此可以与现有的S3工具和库无缝集成。MinIO的设计目标是高性能、高可用性和可扩展性。它可以在分布式模式下运行,以满足不同规模的存储需求。 MinIO是

    2024年02月04日
    浏览(46)
  • 开源对象存储服务器MinIO本地部署并结合内网穿透实现远程访问管理界面

    MinIO是一个开源的对象存储服务器,可以在各种环境中运行,例如本地、Docker容器、Kubernetes集群等。它兼容Amazon S3 API,因此可以与现有的S3工具和库无缝集成。MinIO的设计目标是高性能、高可用性和可扩展性。它可以在分布式模式下运行,以满足不同规模的存储需求。 MinIO是

    2024年02月01日
    浏览(33)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包