欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Minio分布式对象存储

程序员文章站 2022-04-18 12:35:12
...

官方参考地址如下:https://docs.min.io/cn/

创建minio服务

下载minio.exe(Windows)

官方下载地址:
https://dl.min.io/server/minio/release/windows-amd64/minio.exe
百度网盘下载地址:
链接:https://pan.baidu.com/s/16xh3EUbcEUkJh6wFZGAhOw
提取码:t5o3

注册服务

先在自己想要用来做存储的盘符下创建一个文件夹
Minio分布式对象存储
cmd将路径切换到D:\Server,因为该路径下有minio.exe
Minio分布式对象存储

Minio分布式对象存储
键入命名minio.exe server D:\Server\minioserver后回车
D:\Server\minioserver为minio存储基础路径
Minio分布式对象存储
初始秘钥为minioadmin,爆红部分的意思是提醒尽快修改秘钥。
访问 http://localhost:9000 登陆(都为minioadmin)
Minio分布式对象存储
Minio分布式对象存储

修改默认秘钥

按照路径打开config.json,搜索access_key、secret_key,修改成自己想要的秘钥保存
Minio分布式对象存储
Minio分布式对象存储
重新注册服务
Minio分布式对象存储

JavaDemo

先在pom.xml中导入依赖包

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

工具类基本变量定义,也可通过配置文件配置

public class OSSUtils {
    protected static String url;
    protected static String accessKey;
    protected static String secretKey;

    static {
        url = "http://127.0.0.1:9000";
        secretKey = "hsf123456";
        accessKey = "hsf123456";
    }
}

上传文件对象实体类

import java.io.InputStream;

public class MultipartFile {

    private String originalFilename;    //存储桶里的对象名称。

    private Long size;                  //对象大小

    private String ContentType;         //

    private InputStream inputStream;    //文件流

    public String getOriginalFilename() {
        return originalFilename;
    }

    public void setOriginalFilename(String originalFilename) {
        this.originalFilename = originalFilename;
    }

    public Long getSize() {
        return size;
    }

    public void setSize(Long size) {
        this.size = size;
    }

    public String getContentType() {
        return ContentType;
    }

    public void setContentType(String contentType) {
        ContentType = contentType;
    }

    public InputStream getInputStream() {
        return inputStream;
    }

    public void setInputStream(InputStream inputStream) {
        this.inputStream = inputStream;
    }
}

文件上传

	/**
     * minio文件上传    通过InputStream上传--流上传
     * @param multipartFile     上传文件对象
     * @param myBucketname      文件夹(桶)名称
     * @return
     */
    public static String minioUploader(MultipartFile multipartFile, String myBucketname){
        try {
            MinioClient mc = MinioClient.builder().endpoint(url).credentials(accessKey, secretKey).build();
            if (!mc.bucketExists(BucketExistsArgs.builder().bucket(myBucketname).build()))
                mc.makeBucket(MakeBucketArgs.builder().bucket(myBucketname).build());

            mc.putObject(
                    PutObjectArgs.builder().bucket(myBucketname).object(multipartFile.getOriginalFilename()).stream(
                            multipartFile.getInputStream(), multipartFile.getSize(), -1)
                            .contentType(multipartFile.getContentType())
                            .build());

            return mc.statObject(StatObjectArgs.builder().
                    bucket(myBucketname).
                    object(multipartFile.getOriginalFilename()).build()).toString();
        } catch (MinioException | NoSuchAlgorithmException | IOException | InvalidKeyException e) {
            return null;
        }
    }

文件下载

	/**
     * 以流的形式下载一个对象
     * @param bucketName    存储桶名称
     * @param objectName    存储桶里的对象名称
     */
    public static void minioDown(String bucketName, String objectName){
        InputStream stream = null;
        try {
            //创建一个MinioClient对象
            MinioClient minioClient = MinioClient.builder().endpoint(url).credentials(accessKey, secretKey).build();
            // 调用statObject()来判断对象是否存在。
            // 如果不存在, statObject()抛出异常,
            // 否则则代表对象存在。
            minioClient.statObject(bucketName, objectName);
            // 获取"myobject"的输入流。
            stream = minioClient.getObject(bucketName, objectName);
            downFile("D:\\1.jpg", stream);
            stream = minioClient.getObject(bucketName, objectName);
            // 读取输入流直到EOF并打印到控制台。
            byte[] buf = new byte[16384];
            int bytesRead;
            while ((bytesRead = stream.read(buf, 0, buf.length)) >= 0) {
                System.out.println(new String(buf, 0, bytesRead));
            }

        } catch (MinioException e) {
            System.out.println("Error occurred: " + e);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } finally {
            try {
                //关闭流
                stream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
	/**
     * 将流转换成文件
     * @param path      文件保存路径
     * @param input     输入流
     */
    private static void downFile(String path, InputStream input) {
        int index;
        FileOutputStream downloadFile = null;
        byte[] bytes = new byte[1024];
        try {
            downloadFile = new FileOutputStream(path);
            while ((index = input.read(bytes)) != -1) {
                downloadFile.write(bytes, 0, index);
                downloadFile.flush();
            }
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            try {
                downloadFile.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

删除文件

	/**
     * 通过文件名 和 文件夹(桶) 名字删除一个对象
     * @param objectname
     * @param myBucketname
     */
    public static void removeObject(String objectname, String myBucketname){
        MinioClient minioClient = MinioClient.builder().endpoint(url).credentials(accessKey, secretKey).build();
        try {
            minioClient.removeObject(RemoveObjectArgs.builder().bucket(myBucketname).object(objectname).build());
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

创建一个新的存储桶

/**
     * 创建一个新的存储桶
     * @param mybucket 存储桶名
     */
    public static void makeBucket(String mybucket){
        MinioClient minioClient = MinioClient.builder().endpoint(url).credentials(accessKey, secretKey).build();
        try {
            // 如存储桶不存在,创建之。
            boolean found = minioClient.bucketExists(mybucket);
            if (found) {
                System.out.println("mybucket already exists");
            } else {
                // 创建名为'my-bucketname'的存储桶。
                minioClient.makeBucket("mybucket");
                System.out.println("mybucket is created successfully");
            }
        } catch (MinioException e) {
            System.out.println("Error occurred: " + e);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        }
    }

删除存储桶

	/**
     * 删除存储桶
     * 不会删除存储桶里的对象,你需要通过removeObject API来删除它们 如果该存储桶下有对象则无法直接删除
     * @param mybucket
     */
    public static void removeBucket(String mybucket) {
        MinioClient minioClient = MinioClient.builder().endpoint(url).credentials(accessKey, secretKey).build();
        try {
            // 删除之前先检查`my-bucket`是否存在。
            boolean found = minioClient.bucketExists(mybucket);
            if (found) {
                // 删除`my-bucketname`存储桶,注意,只有存储桶为空时才能删除成功。
                minioClient.removeBucket("mybucket");
                System.out.println("mybucket is removed successfully");
            } else {
                System.out.println("mybucket does not exist");
            }
        } catch (MinioException e) {
            System.out.println("Error occurred: " + e);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        }
    }

获取所有的存储桶

	/**
     * 获取所有的存储桶
     */
    public static List<Bucket> getBucketList(){
        MinioClient minioClient = MinioClient.builder().endpoint(url).credentials(accessKey, secretKey).build();
        List<Bucket> bucketList = null;
        try {
            // 获取所有存储桶
            bucketList = minioClient.listBuckets();
        } catch (MinioException e) {
            System.out.println("Error occurred: " + e);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        }
        return bucketList;
    }

获取某一存储桶下所有对象

/**
     * 获取某一存储桶下所有对象
     */
    public static void getObjectList(String mybucket){
        MinioClient minioClient = MinioClient.builder().endpoint(url).credentials(accessKey, secretKey).build();
        try {
            // 检查'mybucket'是否存在。
            boolean found = minioClient.bucketExists(mybucket);
            if (found) {
                // 列出'my-bucketname'里的对象
                Iterable<Result<Item>> myObjects = minioClient.listObjects(mybucket);
                for (Result<Item> result : myObjects) {
                    Item item = result.get();
                    System.out.println(item.lastModified() + ", " + item.size() + ", " + URLDecoder.decode(item.objectName(), "utf-8"));
                }
            } else {
                System.out.println(mybucket+" does not exist");
            }
        } catch (MinioException e) {
            System.out.println("Error occurred: " + e);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        }
    }