iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > JAVA >MinIO的安装与使用
  • 593
分享到

MinIO的安装与使用

linux开发语言java服务器 2023-08-18 19:08:09 593人浏览 独家记忆
摘要

MiNIO的安装与使用 一、MinIO是什么?二、MinIO安装(centos7)2.1 下载MinIO2.2 启动MinIO2.3 修改配置2.4 编写启动脚本,以及加入到systemctl中 三、Springboot集成Mi

一、Minio是什么?

  • MinIO 是一款高性能、分布式的对象存储系统. 它是一款软件产品, 可以100%的运行在标准硬件。即X86等低成本机器也能够很好的运行MinIO。

  • MinIO与传统的存储和其他的对象存储不同的是:它一开始就针对性能要求更高的私有云标准进行软件架构设计。因为MinIO一开始就只为对象存储而设计。所以他采用了更易用的方式进行设计,它能实现对象存储所需要的全部功能,在性能上也更加强劲,它不会为了更多的业务功能而妥协,失去MinIO的易用性、高效性。 这样的结果所带来的好处是:它能够更简单的实现局有弹性伸缩能力的原生对象存储服务。

  • MinIO在传统对象存储用例(例如辅助存储,灾难恢复和归档)方面表现出色。同时,它在机器学习大数据、私有云、混合云等方面的存储技术上也独树一帜。当然,也不排除数据分析、高性能应用负载、原生云的支持。

  • MinIO主要采用golang语言实现,,客户端与存储服务器之间采用Http/https通信协议。

  • 它与 Amazon S3 云存储服务 api 兼容

    MinIO的相关信息

    中文官网: http://www.minio.org.cn/
    中文文档: http://docs.minio.org.cn/docs/
    中文下载地址:http://www.minio.org.cn/download.shtml#/linux
    英文官网: https://min.io/
    英文文档: https://docs.min.io/
    英文下载地址:https://min.io/download#/linux
    GitHub地址:https://github.com/minio/minio

二、MinIO安装(Centos7)

2.1 下载MinIO

演示以官网下载二进制文件配置,下载地址见上方,,,,Docker安装更简单哦~

#创建目录mkdir /usr/local/minio/cd /usr/local/minio/#下载并添加权限wget http://dl.minio.org.cn/server/minio/release/linux-amd64/minio#赋值权限chmod +x minio

2.2 启动MinIO

#创建数据目录,数据目录存储需要大点mkdir -p /home/data/minio#创建日志目录mkdir -p /home/data/minio/logtouch /home/data/minio/log/minio.log#前台启动minio./minio server /home/data/minio#后台启动minionohup ./minio server /home/data/minio > /home/data/minio/log/minio.log &# nohup端口自定义启动服务 指定文件存放路径 /home/data/minio 还有设置日志文件路径 /home/data/minio/log/minio.lognohup ./minio server --address :9000 --console-address :9001 /home/data/minio > /home/data/minio/log/minio.log 2>&1 &

–address :9000 --console-address :9001 是配置端口,默认minio端口是9000,如果9000端口被占用了,那就加上这一串配置,端口号的冒号之前不需要特意写出ip,当然如果你的ip的动态变化的,而不是静态的话,前边的ip不用写上,当然最好是用静态的ip

在这里插入图片描述

关闭防火墙
如果未关闭,输入以下命令:

systemctl stop firewalld

注意:如果不想关闭防火墙,需要开放ip端口9000和设置静态控制访问IP

访问:http://192.168.92.100:9000查看控制台
这里我们都使用的默认配置账号密码 minioadmin:minioadmin

在这里插入图片描述

2.3 修改配置

这里账号和密码都是用的默认的,如果我们要修改可以在环境变量里设置
修改环境变量

  1. 打开 /etc/profile 文件

    vim /etc/profile
  2. 在文件的最末尾加上以下信息(启动的时候看提示,新版本需要用MINIO_ROOT_USERMINIO_ROOT_PASSWord,旧版需要用MINIO_ACCESS_KEYMINIO_SECRET_KEY)。
    在这里插入图片描述
    按 i 键后,在文档末尾输入
    (1)新版:

    export MINIO_ROOT_USER=minioadminexport MINIO_ROOT_PASSWORD=admin123

    (2)旧版

    export MINIO_ACCESS_KEY=minioadminexport MINIO_SECRET_KEY=admin123
  3. 保存退出,刷新重载环境变量

    source /etc/profile

2.4 编写启动脚本,以及加入到systemctl中

为了方便管理,我们这里给命令添加到脚本中

  1. /usr/local/minio/目录下新建run.sh

    vim run.sh
  2. 然后将以下内容保存到run.sh,并为其赋予执行权限chmod +x run.sh

    #!/bin/bash#配置登陆账号密码export MINIO_ROOT_USER=minioadminexport MINIO_ROOT_PASSWORD=admin123# nohup启动服务 指定文件存放路径 /home/data/minio 还有设置日志文件路径 /home/data/minio/log/minio.lognohup ./minio server --address :9000 --console-address :9001 /home/data/minio > /home/data/minio/log/minio.log 2>&1 &
  3. 然后启动minio

    # 启动minio服务bash run.sh# 查看日志tail -200f /home/data/minio/log/minio.log

    在这里插入图片描述

    然后会有日志打印信息,然后可以看到minio服务器地址,和控制台信息地址

    然后在浏览器中访问地址http://192.168.92.100:9000,输入这个地址后会重定向到控制台登录地址http://192.168.92.100:9001/login

添加到systemctl启动命令中

  1. 编写minio.service文件

    vim /usr/lib/systemd/system/minio.service

    填写以下内容

    [Unit]Description=minioDocumentation=https://docs.min.ioWants=network-online.targetAfter=network-online.targetAssertFileIsExecutable=/usr/local/minio/minio[Service]#User and groupUser=rootGroup=rootExecStart=/usr/local/minio/run.sh#Let systemd restart this service alwaysRestart=always#Specifies the maximum file descriptor number that can be opened by this processLimitNOFILE=65536#Disable timeout logic and wait until process is stoppedTimeoutStopSec=infinitySendSIGKILL=no[Install]WantedBy=multi-user.target
  2. 赋值权限并且启动

    chmod +x /usr/lib/systemd/system/minio.service

    启动、查看、设置开机启动

    systemctl daemon-reloadsystemctl start miniOSystemctl enable miniosystemctl status minio

    启动报错处理

    在这里插入图片描述

    systemctl start minioAssertion failed on job for minio.service.# 是 minio.service 的 AssertFileIsExecutable 路径错误AssertFileIsExecutable=/usr/local/minio# 改为AssertFileIsExecutable=/usr/local/minio/minio

到这里单机版的已经安装完毕!

三、SpringBoot集成MinIO

3.1 项目应用

  1. 项目的pom文件中引入minio依赖
<properties>        <minio.version>7.1.0</minio.version> <dependencies>        <dependency>            <groupId>io.minio</groupId>            <artifactId>minio</artifactId>            <version>${minio.version}</version>        </dependency> </dependencies>
  1. application.yml文件中配置minio
minio:  endpoint: http://192.168.92.100  port: 9000  accessKey: minioadmin  secreTKEy: admin123  bucketName: test  secure: false spring:#设置文件上传大小限制  servlet:    multipart:      max-file-size: 100MB      max-request-size: 150MB
  1. 创建minio配置类和工具
    配置类:
package cn.cvzhanshi.wechatpush.config;import io.minio.Minioclient;import io.minio.errors.InvalidPortException;import lombok.Getter;import lombok.Setter;import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.stereotype.Component;@Configuration@Component@ConfigurationProperties(prefix = "minio")@Getter@Setterpublic class MinioConfig {    private String endpoint;    private int port;    private String accessKey;    private String secretKey;    private Boolean secure;    private String bucketName;    @Bean    public MinioClient getMinioClient() throws InvalidPortException {        MinioClient minioClient = MinioClient.builder().endpoint(endpoint, port, secure)                .credentials(accessKey, secretKey)                .build();        return minioClient;    }////    @Bean(name = "multipartResolver")//    public MultipartResolver multipartResolver(){//        CommonsMultipartResolver resolver = new CommonsMultipartResolver();//        resolver.setDefaultEncoding("UTF-8");//        //resolveLazily属性启用是为了推迟文件解析,以在在UploadAction中捕获文件大小异常//        resolver.setResolveLazily(true);//        resolver.setMaxInMemorySize(40960);//        //上传文件大小 50M 50*1024*1024//        resolver.setMaxUploadSize(50*1024*1024);//        return resolver;//    }}

工具类:

package cn.cvzhanshi.wechatpush.utils;import io.minio.*;import io.minio.errors.*;import io.minio.http.Method;import io.minio.messages.Bucket;import io.minio.messages.DeleteError;import io.minio.messages.DeleteObject;import io.minio.messages.Item;import lombok.extern.slf4j.Slf4j;import org.apache.commons.lang3.StringUtils;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Component;import org.springframework.WEB.multipart.MultipartFile; import javax.servlet.ServletOutputStream;import javax.servlet.http.HttpServletResponse;import java.io.IOException;import java.io.InputStream;import java.nio.charset.StandardCharsets;import java.security.InvalidKeyException;import java.security.NoSuchAlGorithmException;import java.util.ArrayList;import java.util.List; @Component@Slf4jpublic class MinioClientUtils {     @Autowired    private MinioClient minioClient;     private static final int DEFAULT_EXPIRY_TIME = 7 * 24 * 3600;         public boolean bucketExists(String bucketName) throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {        boolean flag = false;        flag = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());        if (flag) {            return true;        }        return false;    }         public boolean makeBucket(String bucketName) throws IOException, InvalidKeyException, InvalidResponseException, RegionConflictException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {        boolean flag = bucketExists(bucketName);        if (!flag) {            minioClient.makeBucket(                    MakeBucketArgs.builder().bucket(bucketName).build());            return true;        } else {            return false;        }    }         public List<String> listBucketNames() throws IOException, InvalidResponseException, InvalidKeyException, NoSuchAlgorithmException, ServerException, ErrorResponseException, XmlParserException, InvalidBucketNameException, InsufficientDataException, InternalException {        List<Bucket> bucketList = listBuckets();        List<String> bucketListName = new ArrayList<>();        for (Bucket bucket : bucketList) {            bucketListName.add(bucket.name());        }        return bucketListName;    }         public List<Bucket> listBuckets() throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {        return minioClient.listBuckets();    }         public boolean removeBucket(String bucketName) throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {        boolean flag = bucketExists(bucketName);        if (flag) {            Iterable<Result<Item>> myObjects = listObjects(bucketName);            for (Result<Item> result : myObjects) {                Item item = result.get();                // 有对象文件,则删除失败                if (item.size() > 0) {                    return false;                }            }            // 删除存储桶,注意,只有存储桶为空时才能删除成功。            minioClient.removeBucket(RemoveBucketArgs.builder().bucket(bucketName).build());            flag = bucketExists(bucketName);            if (!flag) {                return true;            }         }        return false;    }         public List<String> listObjectNames(String bucketName) throws XmlParserException, IOException, InvalidResponseException, InvalidKeyException, NoSuchAlgorithmException, ServerException, ErrorResponseException, InvalidBucketNameException, InsufficientDataException, InternalException {        List<String> listObjectNames = new ArrayList<>();        boolean flag = bucketExists(bucketName);        if (flag) {            Iterable<Result<Item>> myObjects = listObjects(bucketName);            for (Result<Item> result : myObjects) {                Item item = result.get();                listObjectNames.add(item.objectName());            }        }        return listObjectNames;    }         public Iterable<Result<Item>> listObjects(String bucketName) throws XmlParserException, IOException, InvalidResponseException, InvalidKeyException, NoSuchAlgorithmException, ServerException, ErrorResponseException, InvalidBucketNameException, InsufficientDataException, InternalException {        boolean flag = bucketExists(bucketName);        if (flag) {            return minioClient.listObjects( ListObjectsArgs.builder().bucket(bucketName).build());        }        return null;    }         public boolean uploadObject(String bucketName, String objectName, String fileName) throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {        boolean flag = bucketExists(bucketName);        if (flag) {            minioClient.uploadObject(                    UploadObjectArgs.builder().bucket(bucketName).object(objectName).filename(fileName).build());            ObjectStat statObject = statObject(bucketName, objectName);            if (statObject != null && statObject.length() > 0) {                return true;            }        }        return false;     }         public void putObject(String bucketName, MultipartFile multipartFile, String filename) throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {        PutObjectOptions putObjectOptions = new PutObjectOptions(multipartFile.getSize(), PutObjectOptions.MIN_MULTIPART_SIZE);        putObjectOptions.setContentType(multipartFile.getContentType());        minioClient.putObject(                PutObjectArgs.builder().bucket(bucketName).object(filename).stream(                        multipartFile.getInputStream(), multipartFile.getSize(), -1).contentType(multipartFile.getContentType())                        .build());    }         public boolean putObject(String bucketName, String objectName, InputStream inputStream,String contentType) throws IOException, InvalidResponseException, InvalidKeyException, NoSuchAlgorithmException, ServerException, ErrorResponseException, XmlParserException, InvalidBucketNameException, InsufficientDataException, InternalException {        boolean flag = bucketExists(bucketName);        if (flag) {            minioClient.putObject(PutObjectArgs.builder().bucket(bucketName).object(objectName).stream(                    //不清楚文件的大小时,可以传-1,10485760。如果知道大小也可以传入size,partsize。                    inputStream,  -1, 10485760)                    .contentType(contentType)                    .build());            ObjectStat statObject = statObject(bucketName, objectName);            if (statObject != null && statObject.length() > 0) {                return true;            }        }        return false;    }         public InputStream getObject(String bucketName, String objectName) throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {        boolean flag = bucketExists(bucketName);        if (flag) {            ObjectStat statObject = statObject(bucketName, objectName);            if (statObject != null && statObject.length() > 0) {                InputStream stream = minioClient.getObject( GetObjectArgs.builder()                        .bucket(bucketName)                        .object(objectName)                        .build());                return stream;            }        }        return null;    }         public InputStream getObject(String bucketName, String objectName, long offset, Long length) throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {        boolean flag = bucketExists(bucketName);        if (flag) {            ObjectStat statObject = statObject(bucketName, objectName);            if (statObject != null && statObject.length() > 0) {                InputStream stream = minioClient.getObject(  GetObjectArgs.builder()                        .bucket(bucketName)                        .object(objectName)                        .offset(1024L)                        .length(4096L)                        .build());                return stream;            }        }        return null;    }         public boolean downloadObject(String bucketName, String objectName, String fileName) throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {        boolean flag = bucketExists(bucketName);        if (flag) {            ObjectStat statObject = statObject(bucketName, objectName);            if (statObject != null && statObject.length() > 0) {                minioClient.downloadObject(DownloadObjectArgs.builder()                        .bucket(bucketName)                        .object(objectName)                        .filename(fileName)                        .build());                return true;            }        }        return false;    }         public boolean removeObject(String bucketName, String objectName) throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {        boolean flag = bucketExists(bucketName);        if (flag) {            minioClient.removeObject(RemoveObjectArgs.builder().bucket(bucketName).object(objectName).build());            return true;        }        return false;    }         public List<String> removeObjects(String bucketName, List<DeleteObject> objectNames) throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {        List<String> deleteErrorNames = new ArrayList<>();        boolean flag = bucketExists(bucketName);        if (flag) {            Iterable<Result<DeleteError>> results = minioClient.removeObjects(RemoveObjectsArgs.builder().bucket(bucketName).objects(objectNames).build());            for (Result<DeleteError> result : results) {                DeleteError error = result.get();                deleteErrorNames.add(error.objectName());            }        }        return deleteErrorNames;    }         public String getPresignedObjectUrl(String bucketName, String objectName, Integer expires) throws InvalidExpiresRangeException, IOException, InvalidResponseException, InvalidKeyException, NoSuchAlgorithmException, ServerException, ErrorResponseException, XmlParserException, InvalidBucketNameException, InsufficientDataException, InternalException {        boolean flag = bucketExists(bucketName);        String url = "";        if (flag) {            if (expires < 1 || expires > DEFAULT_EXPIRY_TIME) {                throw new InvalidExpiresRangeException(expires,                        "expires must be in range of 1 to " + DEFAULT_EXPIRY_TIME);            }            try {                url = minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder()                        .method(Method.GET)                        .bucket(bucketName)                        .object(objectName)                        .expiry(expires)//动态参数                        //                       .expiry(24 * 60 * 60)//用秒来计算一天时间有效期//                        .expiry(1, TimeUnit.DAYS)//按天传参//                        .expiry(1, TimeUnit.HOURS)//按小时传参数                        .build());            } catch (ErrorResponseException | InsufficientDataException | InternalException | InvalidBucketNameException | InvalidExpiresRangeException | InvalidKeyException | InvalidResponseException | IOException | NoSuchAlgorithmException | ServerException | XmlParserException e) {                e.printStackTrace();            }        }        return url;    }         public String presignedPutObject(String bucketName, String objectName, Integer expires) throws IOException, InvalidResponseException, InvalidKeyException, NoSuchAlgorithmException, ServerException, ErrorResponseException, XmlParserException, InvalidBucketNameException, InsufficientDataException, InternalException {        boolean flag = bucketExists(bucketName);        String url = "";        if (flag) {            if (expires < 1 || expires > DEFAULT_EXPIRY_TIME) {                try {                    throw new InvalidExpiresRangeException(expires,"expires must be in range of 1 to " + DEFAULT_EXPIRY_TIME);                } catch (InvalidExpiresRangeException e) {                    e.printStackTrace();                }            }            try {                url = minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder()                        .method(Method.PUT)                        .bucket(bucketName)                        .object(objectName)                        .expiry(expires)//动态参数                        //                       .expiry(24 * 60 * 60)//用秒来计算一天时间有效期//                        .expiry(1, TimeUnit.DAYS)//按天传参//                        .expiry(1, TimeUnit.HOURS)//按小时传参数                        .build());            } catch (ErrorResponseException | InsufficientDataException e) {                e.printStackTrace();            } catch (InternalException e) {                log.error("InternalException",e);            } catch (InvalidBucketNameException e) {                log.error("InvalidBucketNameException",e);            } catch (InvalidExpiresRangeException e) {                log.error("InvalidExpiresRangeException",e);            } catch (InvalidKeyException e) {                log.error("InvalidKeyException",e);            } catch (InvalidResponseException e) {                log.error("InvalidResponseException",e);            } catch (IOException e) {                log.error("IOException",e);            } catch (NoSuchAlgorithmException e) {                log.error("NoSuchAlgorithmException",e);            } catch (ServerException e) {                log.error("ServerException",e);            } catch (XmlParserException e) {                log.error("XmlParserException",e);            }        }        return url;    }         public ObjectStat statObject(String bucketName, String objectName) throws IOException, InvalidResponseException, InvalidKeyException, NoSuchAlgorithmException, ServerException, ErrorResponseException, XmlParserException, InvalidBucketNameException, InsufficientDataException, InternalException {        boolean flag = bucketExists(bucketName);        if (flag) {            ObjectStat statObject = null;            try {                statObject = minioClient.statObject(StatObjectArgs.builder().bucket(bucketName).object(objectName).build());            } catch (ErrorResponseException e) {                log.error("ErrorResponseException",e);            } catch (InsufficientDataException e) {                log.error("ErrorResponseException",e);                e.printStackTrace();            } catch (InternalException e) {                log.error("InternalException",e);            } catch (InvalidBucketNameException e) {                log.error("InvalidBucketNameException",e);            } catch (InvalidKeyException e) {                log.error("InvalidKeyException",e);            } catch (InvalidResponseException e) {                log.error("InvalidResponseException",e);            } catch (IOException e) {                log.error("IOException",e);            } catch (NoSuchAlgorithmException e) {                log.error("NoSuchAlgorithmException",e);            } catch (ServerException e) {                log.error("ServerException",e);            } catch (XmlParserException e) {                log.error("XmlParserException",e);            }            return statObject;        }        return null;    }         public String getObjectUrl(String bucketName, String objectName) throws IOException, InvalidResponseException, InvalidKeyException, NoSuchAlgorithmException, ServerException, ErrorResponseException, XmlParserException, InvalidBucketNameException, InsufficientDataException, InternalException {        boolean flag = bucketExists(bucketName);        String url = "";        if (flag) {            try {                url = minioClient.getObjectUrl(bucketName, objectName);            } catch (ErrorResponseException e) {                log.error("XmlParserException",e);            } catch (InsufficientDataException e) {                log.error("InsufficientDataException",e);            } catch (InternalException e) {                log.error("InternalException",e);            } catch (InvalidBucketNameException e) {                log.error("InvalidBucketNameException",e);            } catch (InvalidKeyException e) {                log.error("InvalidKeyException",e);            } catch (InvalidResponseException e) {                log.error("InvalidResponseException",e);            } catch (IOException e) {                log.error("IOException",e);            } catch (NoSuchAlgorithmException e) {                log.error("NoSuchAlgorithmException",e);            } catch (ServerException e) {                log.error("ServerException",e);            } catch (XmlParserException e) {                log.error("XmlParserException",e);            }        }        return url;    }       public void downloadFile(String bucketName, String fileName, String originalName, HttpServletResponse response) {        try {             InputStream file = minioClient.getObject(GetObjectArgs.builder()                    .bucket(bucketName)                    .object(fileName)                    .build());            String filename = new String(fileName.getBytes("ISO8859-1"), StandardCharsets.UTF_8);            if (StringUtils.isNotEmpty(originalName)) {                fileName = originalName;            }            response.setHeader("Content-Disposition", "attachment;filename=" + filename);            ServletOutputStream servletOutputStream = response.getOutputStream();            int len;            byte[] buffer = new byte[1024];            while ((len = file.read(buffer)) > 0) {                servletOutputStream.write(buffer, 0, len);            }            servletOutputStream.flush();            file.close();            servletOutputStream.close();        } catch (ErrorResponseException e) {            log.error("ErrorResponseException",e);        } catch (Exception e) {            log.error("Exception",e);        }    }} 
  1. 创建一个数据表,用于保存上传到minio的文件的信息

    CREATE TABLE `minio_file` (  `id` bigint(20) NOT NULL COMMENT '文件id',  `original_file_name` varchar(255) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '原始文件名称',  `file_ext_name` varchar(15) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '文件拓展名',  `file_size` bigint(20) DEFAULT NULL COMMENT '文件大小(单位:字节)',  `file_name` varchar(35) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '存入minio时的文件名称',  `mime` varchar(50) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '文件的content-type',  `file_url` varchar(255) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '文件路径',  `is_delete` tinyint(1) DEFAULT NULL COMMENT '是否删除 0 否 1 是',  `create_by` varchar(25) COLLATE utf8mb4_bin DEFAULT NULL,  `create_time` datetime DEFAULT NULL,  `update_by` varchar(25) COLLATE utf8mb4_bin DEFAULT NULL,  `update_time` datetime DEFAULT NULL,  PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
  2. 创建minio上传接口

    package cn.cvzhanshi.wechatpush.controller;import cn.cvzhanshi.wechatpush.config.MinioConfig;import cn.cvzhanshi.wechatpush.utils.MinioClientUtils;import cn.hutool.core.io.FileUtil;import io.swagger.annotations.Api;import io.swagger.annotations.ApiImplicitParam;import io.swagger.annotations.ApiImplicitParams;import io.swagger.annotations.ApiOperation;import lombok.AllArgsConstructor;import lombok.extern.slf4j.Slf4j;import org.apache.commons.lang3.RandomStringUtils;import org.apache.commons.lang3.math.NumberUtils;import org.springframework.stereotype.Controller;import org.springframework.util.CollectionUtils;import org.springframework.web.bind.annotation.*;import org.springframework.web.multipart.MultipartFile;import java.io.FileInputStream;import java.time.Instant;import java.util.ArrayList;import java.util.List;@RestController@RequestMapping("/fileHandle")@Slf4j@AllArgsConstructor@Api(tags = "文件处理模块")public class FileHandleController {private MinioClientUtils minioClientUtils;private MinioConfig minioConfig;@ApiOperation(value = "上传文件,支持批量上传")@ApiImplicitParams({@ApiImplicitParam(name = "files", value = "文件流对象,接收数组格式", paramType = "query",required = true, dataType = "MultipartFile", allowMultiple = true)})@PostMapping("/uploadFile")public ApiResult uploadFile(@RequestParam(value = "files", required = true) MultipartFile[] files) {log.info(files.toString());     List<String> MinioResponseDTOList = new ArrayList<>();for (MultipartFile file : files) {String originalFilename = file.getOriginalFilename();//            获取文件拓展名String extName = FileUtil.extName(originalFilename);log.info("文件拓展名:" + extName);//            生成新的文件名,存入到miniolong millSeconds = Instant.now().toEpochMilli();String minioFileName = millSeconds + RandomStringUtils.randomNumeric(12) + "." + extName;String contentType = file.getContentType();log.info("文件mime:{}", contentType);//            返回文件大小,单位字节long size = file.getSize();log.info("文件大小:" + size);try {String bucketName = minioConfig.getBucketName();minioClientUtils.putObject(bucketName, file, minioFileName);String fileUrl = minioClientUtils.getObjectUrl(bucketName, minioFileName);             MinioResponseDTOList.add(fileUrl);} catch (Exception e) {log.error("上传文件出错:{}", e);return ApiResult.error("上传文件出错");}}return ApiResult.success(MinioResponseDTOList);}@GetMapping("/test")@ApiOperation(value = "测试minio文件上传")public ApiResult testPutObject() throws Exception {FileInputStream fileInputStream = new FileInputStream("C:\\Users\\MSI\\Desktop\\新建文本文档.txt");boolean bs = minioClientUtils.putObject("fsp-dev", "新建文本文档.txt", fileInputStream, "image/jpg");log.info("上传成功?" + bs);return ApiResult.success("上传成功");}}
  3. 测试接口
    在这里插入图片描述

四、Java中图片压缩上传

4.1 背景

现在大家都是用的智能手机拍照,拍出来的照片小则 2-3 M,大则十几 M,所以导致图片显示较慢。思考再三,决定将图片进行压缩再上传图片服务器来解决图片显示慢的问题

4.2 开发准备

  1. 引入 Maven 依赖

    <!-- 图片压缩 --><dependency>    <groupId>net.coobird</groupId>    <artifactId>thumbnailator</artifactId>    <version>0.4.8</version></dependency>

    本次我们选择了使用 thumbnailator 来作为压缩的工具

  2. thumbnailator 简介

    Thumbnailator 是一个用来生成图像缩略图的 Java 类库,通过很简单的代码即可生成图片缩略图,也可直接对一整个目录的图片生成缩略图
    支持图片缩放,区域裁剪,水印,旋转,保持比例

  3. 压缩准备
    判断是否是图片方法

    public boolean isPicture(String imgName) {    boolean flag = false;    if (StringUtils.isBlank(imgName)) {        return false;    }    String[] arr = {"bmp", "dib", "gif", "jfif", "jpe", "jpeg", "jpg", "png", "tif", "tiff", "ico"};    for (String item : arr) {        if (item.equals(imgName)) {            flag = true;            break;        }    }    return flag;}

4.3 压缩上传

public JSONObject uploadFile(MultipartFile file) throws Exception {    jsONObject res = new JSONObject();    res.put("code", 500);    // 判断上传文件是否为空    if (null == file || 0 == file.getSize()) {        res.put("msg", "上传文件不能为空");        return res;    }    // 判断存储桶是否存在    if (!client.bucketExists("test")) {        client.makeBucket("test");    }    // 拿到文件后缀名,例如:png    String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);    // UUID 作为文件名    String uuid = String.valueOf(UUID.randomUUID());    // 新的文件名    String fileName = DateUtils.getYyyymmdd() + "/" + uuid + "." + suffix;        if (isPicture(suffix) && (1024 * 1024 * 0.1) <= file.getSize()) {        // 在项目根目录下的 upload 目录中生成临时文件        File newFile = new File(ClassUtils.getDefaultClassLoader().getResource("upload").getPath() + uuid + "." + suffix);        // 小于 1M 的        if ((1024 * 1024 * 0.1) <= file.getSize() && file.getSize() <= (1024 * 1024)) {            Thumbnails.of(file.getInputStream()).scale(1f).outputQuality(0.3f).toFile(newFile);        }        // 1 - 2M 的        else if ((1024 * 1024) < file.getSize() && file.getSize() <= (1024 * 1024 * 2)) {            Thumbnails.of(file.getInputStream()).scale(1f).outputQuality(0.2f).toFile(newFile);        }        // 2M 以上的        else if ((1024 * 1024 * 2) < file.getSize()) {            Thumbnails.of(file.getInputStream()).scale(1f).outputQuality(0.1f).toFile(newFile);        }        // 获取输入流        FileInputStream input = new FileInputStream(newFile);        // 转为 MultipartFile        MultipartFile multipartFile = new MockMultipartFile("file", newFile.getName(), "text/plain", input);        // 开始上传        client.putObject("test", fileName, multipartFile.getInputStream(), file.getContentType());        // 删除临时文件        newFile.delete();        // 返回状态以及图片路径        res.put("code", 200);        res.put("msg", "上传成功");        res.put("url", minioProp.getEndpoint() + "/" + "test" + "/" + fileName);    }    // 不需要压缩,直接上传    else {        // 开始上传        client.putObject("test", fileName, file.getInputStream(), file.getContentType());        // 返回状态以及图片路径        res.put("code", 200);        res.put("msg", "上传成功");        res.put("url", minioProp.getEndpoint() + "/" + "test" + "/" + fileName);    }    return res;}
  • 这里我们判断了当文件为图片的时候,且当它大小超过了 (1024 * 1024 * 0.1),约为 100K 的时候,才进行压缩
  • 我们首先在根目录下的 upload 目录中创建了一个临时文件 newFile
  • Thumbnails.of(file.getInputStream()).scale(1f).outputQuality(0.3f).toFile(newFile);将压缩后的文件输出到临时文件中
  • 然后将 FileInputStream 转为 MultipartFile 上传
  • 最后删除临时文件 newFile.delete();
  • 完成图片压缩上传

遇到的问题:
Thumbnails.scale效果会导致图片大小变大
在这里插入图片描述

Thumbnails应该是存在bug,但是也一直没有更新版本,所以根据多次测试得来的结果:用jpg转成jpg效果最佳。所以当图片为png时,先改成jpg格式,再进行压缩。

public static String imGConvert(String tempDirPath, String fileName, String fileExt) throws IOException {    String srcPath = tempDirPath + fileName;  //原始图片路径    if("png".equals(fileExt)) {        //生成新图片名称    SimpleDateFORMat df = new SimpleDateFormat("yyyyMMddHHmmss");            String fileString = df.format(new Date()) + "_" + new Random().nextInt(1000) + ".jpg";                        //新图片全路径            String newJpg = tempDirPath + fileString;                     // 1、先转换成jpg              Thumbnails.of(srcPath).scale(1f).toFile(newJpg);                         //2.jpg图片压缩            Thumbnails.of(newJpg).scale(1f).outputQuality(0.25d).toFile(newJpg);                        //压缩成功后,删除png图片            File f = new File(srcPath);            f.delete();                        return fileString;    } else {    Thumbnails.of(srcPath).scale(1f).outputQuality(0.25d).toFile(srcPath);    }    return null;    }

五、MinIO集群搭建(完善中~)

来源地址:https://blog.csdn.net/qq_38055805/article/details/130216715

--结束END--

本文标题: MinIO的安装与使用

本文链接: https://www.lsjlt.com/news/374583.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • MinIO的安装与使用
    MinIO的安装与使用 一、MinIO是什么?二、MinIO安装(centos7)2.1 下载MinIO2.2 启动MinIO2.3 修改配置2.4 编写启动脚本,以及加入到systemctl中 三、Springboot集成Mi...
    99+
    2023-08-18
    linux 开发语言 java 服务器
  • minio安装与数据迁移
    minio安装与数据迁移 一、minio安装1.下载二进制文件minio2.将minio上传到服务器并授予可执行权限3.创建用户4.启动minio5.查看minio启动状态6.访问并创建桶 ...
    99+
    2023-09-05
    linux 服务器 bash
  • linux下怎么使用docker安装minio
    这篇文章主要介绍“linux下怎么使用docker安装minio”,在日常操作中,相信很多人在linux下怎么使用docker安装minio问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”linux下怎么使用d...
    99+
    2023-07-05
  • linux下如何使用docker安装minio
    目录docker 安装 miniodocker离线(升级)安装MINIO1.查看版本2.本地安装3.把包上传到服务器总结docker 安装 minio 1、拉取 minio 镜像 pull minio/minio 2、创...
    99+
    2023-04-03
    linux使用docker docker安装minio linux docker安装minio
  • linux centos安装minio
    第一步,进入/opt 目录,创建minio文件夹 cd /opt mkdir minio 第二步,wget下载安装包: 命令 :wegt https://dl.minio.io/server/mini...
    99+
    2023-10-02
    linux centos 服务器
  • linux下安装minio
    获取 MinIO 下载 URL:访问:https://docs.min.io/ 一,进入/opt 目录,创建minio文件夹 cd /opt mkdir minio 二,wget下载安装包 wget https://dl.minio.io/...
    99+
    2023-08-18
    linux 服务器 运维
  • Linux 下安装Minio
    1、下载Minio 参考官方文档https://www.minio.org.cn/download.shtml#/linux 创建minio目录 makedir /home/minio cd  /home/minio 下载 wget htt...
    99+
    2023-10-09
    linux 服务器 运维
  • minio安装部署及使用的详细过程
    目录一、服务器安装minio1.进行下载2.新建minio安装目录,执行如下命令二、进行访问,并设置桶1.访问 三、springboot进行实现1.引入依赖2.在 appl...
    99+
    2024-04-02
  • MinIO存储在docker中安装及其使用方式
    目录MinIO存储在docker安装及使用MinIOdocker 安装Miniojava代码操作Docker-compose安装部署MinIO存储服务环境准备启动容器并访问总结Min...
    99+
    2023-05-14
    MinIO存储 docker安装 docker使用
  • Minio使用
    MinIO 是在 GNU Affero 通用公共许可证 v3.0 下发布的高性能对象存储。它与 Amazon S3 云存储服务 API 兼容。使用 MinIO 为机器学习、分析和应用程序数据工作负载构建高性能基础架构。 MinIO...
    99+
    2023-08-17
    java 数据库 redis
  • 云服务器 docker 安装 MinIO
     执行命令 docker pull minio/minio 下载稳定版本镜像 docker pull minio/minio  创建并启动minio容器  MINIO_ACCESS_KEY是登录的用户名,MINIO_SECRET_K...
    99+
    2023-09-11
    docker 运维 MinIO
  • tcpreplay的安装与使用
    一、背景介绍 tcpreplay是一种pcap包的重放工具, 它可以将用ethreal, wireshark工具抓下来的包原样或经过任意修改后重放回去. 它允许你对报文做任意的修改(主要是指对2层, ...
    99+
    2023-10-24
    网络 linux 服务器 tcp
  • npm的安装与使用
    目录一、由来1、在 GitHub 还没有兴起的年代,前端是通过网址来共享代码2、GItHub 兴起之后,社区中也有人使用 GitHub 的下载功能:3、麻烦4、具体步骤5、发展二、n...
    99+
    2024-04-02
  • sshpass的安装与使用
    1. sshpass的定义与安装 (1)定义 sshpass 的定义:ssh 登陆不能在命令行中指定密码,sshpass 的出现则解决了这一问题。它允许你用 -p 参数指定明文密码,然后直接登录远程服务器,它支持密码从命令行、文件、环境变量...
    99+
    2023-09-01
    linux sshpass scp ssh 脚本
  • MinIO存储在docker中安装及使用的方法是什么
    本篇内容主要讲解“MinIO存储在docker中安装及使用的方法是什么”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“MinIO存储在docker中安装及使用的方法是什么”吧!MinIO存储在do...
    99+
    2023-07-05
  • docker安装minio无法访问的解决
    目录docker安装minio无法访问1、执行命令docker search minio2、执行docker pull minio/minio安装minio3、指定端口启动,这里有个...
    99+
    2023-05-14
    docker安装minio 安装minio无法访问 docker安装minio无法访问
  • Composer 安装与使用
    一、composer 安装 进入系统的  cd /usr/local/bin   目录 执行安装命令: curl -sS https://getcomposer.org/installer | php 重命名 composer.phar...
    99+
    2023-09-04
    composer php 开发语言
  • Minio与SpringBoot使用okhttp3问题解决
    目录抛砖追影完璧抛砖 今天使用monio做S3存储时,添加云服务器初始化时一直在构建客户端抛出异常。 MinioClient.builder() //NoClassDefFo...
    99+
    2022-11-13
    Minio SpringBoot使用okhttp3 Minio SpringBoot
  • Vue安装与使用
    目录1、Vue安装方式1:CDN引入方式2:直接下载引入方式3:npm安装2、基本使用前言: Vue(读音/vjuː/,类似于view) 是一套用于构建前后端分离的框架。刚...
    99+
    2024-04-02
  • WinHex安装与使用
    目录 下载WinHex 安装WinHex 查看现成的磁盘文件 手动创建磁盘文件 创建磁盘文件 创建分区 安装引导程序 查看磁盘 下载WinHex 下载链接: WinHex: Hex Editor & Disk Editor, Comp...
    99+
    2023-09-06
    linux 运维 服务器
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作