MinIO

MinIO 是一个基于Apache License v2.0开源协议的对象存储服务。它兼容亚马逊S3云存储服务接口,非常适合于存储大容量非结构化的数据,例如图片、视频、日志文件、备份数据和容器/虚拟机镜像等,而一个对象文件可以是任意大小,从几kb到最大5T不等。

MinIO是一个非常轻量的服务,可以很简单的和其他应用的结合,类似 NodeJS, Redis 或者 MySQL

一、docker 安装Minio

安装docker镜像

# docker安装镜像
docker pull minio/minio

容器运行方式① 和 容器运行方式② 选择一种就好。

运行容器方式①

# 后台运行容器
docker run -p 9000:9000 --name storage -di -v /storage/data:/data -v /storage/config:/root/.minio --restart=always minio/minio server /data

1,进入容器
docker exec -it storage sh

2,查看配置文件中的key值
cat /data/.minio.sys/config/config.json |grep Key
“accessKey”: “507LX5P57F99DNEVF1GH”,
“secretKey”: “Kc2tllnd9FQrgTzu0RSohir4B4svh2cLiueGZR5x”,
“routingKey”: “”,

运行容器方式②

# 后台运行容器方式
docker run -p 9000:9000 --name storage -di --restart=always \
  -e "MINIO_ACCESS_KEY=superzheng" \
  -e "MINIO_SECRET_KEY=storage/File" \
  -v /storage/data:/data \
  -v /storage/config:/root/.minio \
  minio/minio server /data
  
# -p 端口映射  将外部端口 映射到 容器内部端口  
# --name 自定义容器名称
# -di 后台运行的方式运行
# --restart=always  一旦docker重启或者开启时,也自动启动镜像
# -e 设置系统变量  在这里是设置Minio的ACCESS_KEY和SECRET_KEY
# -v 挂载文件  将系统文件  映射到  容器内部对应的文件夹
  

这是安装成功的日志:

更多信息:请访问官网 https://docs.min.io/cn/

二、java代码操作

package cn.mesmile.oss.minio;

import cn.hutool.core.util.StrUtil;
import cn.mesmile.oss.domain.FileInfoResp;
import cn.mesmile.oss.exception.BucketNotExistException;
import cn.mesmile.oss.exception.ContentTypeException;
import cn.mesmile.oss.exception.FileSizeMaxException;
import io.minio.MinioClient;
import io.minio.Result;
import io.minio.messages.DeleteError;
import io.minio.policy.PolicyType;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

/**
 * @author zb
 * @date 2019/12/15 14:20
 * @Description:
 * Copyright (C),2019,AOSSCI Inc.傲势科技有限公司
 *   Endpoint	对象存储服务的URL
 *   Access key就像用户ID,可以唯一标识你的账户。
 *   Secret key是你账户的密码。
 */
@Component
public class FileService {

    /**
     * 对象存储服务的URL, 注意 这里的endpoint填写 url会报错,这里endpoint的值应该为 【 http://ip:端口号 】 的形式  
     */
    @Value("${minio.endpoint}")
    private  String endpoint;

    /**
     * 就像用户ID,可以唯一标识你的账户
     */
    @Value("${minio.access-key}")
    private  String accessKey;

    /**
     * 是你账户的密码
     */
    @Value("${minio.secret-key}")
    private  String secretKey;

    // 上传的最大限制 10 M
    private static final long MAX_SIZE =1024*1024*100;

    /**
     *  上传图片
     * @param bucketName  桶名称
     * @param file        文件
     * @return
     * @throws Exception
     */
    public FileInfoResp uploadImage(String bucketName, MultipartFile file) throws Exception{
        String contentType = file.getContentType();
        // image/png
        if (!StrUtil.containsAny(contentType,"image")) {
            throw new ContentTypeException("文件类型错误,请上传图片文件。");
        }
        return uploadFile(bucketName,file,"image");
    }

    /**
     * 上传文件
     * @param bucketName 桶名
     * @param file  文件
     * @return
     * @throws Exception
     */
    public FileInfoResp uploadFile(String bucketName, MultipartFile file) throws Exception {
        String contentType = file.getContentType();
        return uploadFile(bucketName,file,contentType);
    }

    /**
     *  删除单个文件
     * @param bucketName
     * @param objectName
     * @return
     * @throws Exception
     */
    public Iterable<Result<DeleteError>> deleteFileSingle(String bucketName, String objectName) throws Exception {
        return deleteFile(bucketName,objectName,null);
    }


    /**
     *  批量删除文件
     * @param bucketName  桶名
     * @param objectNames 批量路径名称
     * @return
     * @throws Exception
     */
    public Iterable<Result<DeleteError>> deleteFileBath(String bucketName, Iterable<String> objectNames) throws Exception {
        return deleteFile(bucketName,null,objectNames);
    }


    /**
     *  删除桶
     * @param bucketName  桶名称
     * @throws Exception
     */
    public void deleteBucket(String bucketName) throws Exception {
        MinioClient minioClient = new MinioClient(endpoint,accessKey,secretKey);
        if (!minioClient.bucketExists(bucketName)) {
            throw new BucketNotExistException("桶不存在");
        }
        minioClient.removeBucket(bucketName);
    }


    /**
     *  删除文件
     * @param bucketName  桶的名称
     * @param objectName  路径名例:  /image/123.jpg
     * @param objectNames 批量路径名:
     * @return
     * @throws Exception
     */
    private Iterable<Result<DeleteError>> deleteFile(String bucketName, String objectName,Iterable<String> objectNames) throws Exception {
        MinioClient minioClient = new MinioClient(endpoint,accessKey,secretKey);
        if (!minioClient.bucketExists(bucketName)) {
            throw new BucketNotExistException("桶不存在");
        }
        if (objectNames != null) {
            return minioClient.removeObject(bucketName, objectNames);
        } else {
            minioClient.removeObject(bucketName, objectName);
            return null;
        }
    }


    /**
     *  上传文件
     * @param bucketName  桶的名称
     * @param file   文件名
     * @param prefix  前缀
     * @return
     * @throws Exception
     */
    private FileInfoResp uploadFile(String bucketName, MultipartFile file, String prefix) throws Exception {
        if (file.getSize() > MAX_SIZE ) {
           throw new FileSizeMaxException("文件过大,超过限制大小:"+MAX_SIZE/(1024*1024.0)+" M");
        }
        MinioClient minioClient = new MinioClient(endpoint,accessKey,secretKey);
        minioClient.setBucketPolicy(bucketName,prefix, PolicyType.READ_WRITE);
        // 检查桶是否存在,若不存在则创建一个
        if (!minioClient.bucketExists(bucketName)) {
            minioClient.makeBucket(bucketName);
        }
        InputStream inputStream = file.getInputStream();
        String contentType = file.getContentType();
        String filename = file.getOriginalFilename();
        String objectName = prefix + "/" +filename;

        // 上传文件
        minioClient.putObject(bucketName,objectName,inputStream,contentType);
        return FileInfoResp.builder()
                .bucketName(bucketName)
                .fileName(filename)
                .objectName(objectName)
                .contentType(contentType)
                .prefix(prefix)
                .url(endpoint + "/" + bucketName + "/" + objectName)
                .build();
    }

}

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐