首页 > 编程语言 >MinIO对象存储 安装和java调用

MinIO对象存储 安装和java调用

时间:2024-05-10 15:27:17浏览次数:23  
标签:调用 java String objectName param bucketName MinioException throws MinIO

1、参考

MinIO对象存储介绍和使用

【备忘录】JAVASDK连接MinIO,附完整代码

2、

package org.j****g.common.util.io;

import cn.hutool.core.io.FileUtil;
import io.minio.*;
import io.minio.errors.MinioException;
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.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.j****g.common.util.CN;
import org.j****g.common.util.DateUtils;
import org.j****g.common.util.network.RedisUtil;
import org.j****g.common.util.spring.SpringContextUtils;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Slf4j
public class MinIoUtil {
    public static void main(String[] args) throws Exception {
        File file = new File("C:\\Users\\e******0\\Desktop\\桌面文件\\测试图 横版01.png");
        String objectName = "img/" + file.getName();

        // MinIoUtil.putObjectByStream(bucketName, objectName, new FileInputStream(file));
        //
        // MinIoUtil.removeObject(objectName);
        //
        // GetObjectResponse response = MinIoUtil.getObject(objectName);
        // File file_dest = new File("C:\\Users\\e******0\\Desktop\\桌面文件\\测试图 横版02.png");
        // FileUtil.writeFromStream(response, file_dest);

        String availableFileUrl = MinIoUtil.getAvailableFileUrl(objectName);
        System.out.println("======availableFileUrl\n" + availableFileUrl);
    }

    private static MinioClient minioClient;
    private static String bucketName;

    static {
        try {
            MinIoConfig minIoConfig = new MinIoConfig("http://127.0.0.1:9000", "minioadmin", "minioadmin", "j****g");
            init(minIoConfig);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void init(MinIoConfig minIoConfig) throws Exception {
        bucketName = minIoConfig.getBucketName();
        minioClient = MinioClient.builder()
                .endpoint(minIoConfig.getEndpoint())
                .credentials(minIoConfig.getAccessKey(), minIoConfig.getSecretKey())
                .build();
        // 初始化Bucket
        initBucket();
        log.info("成功连接上minio.URL:{} ,bucket {}", minIoConfig.getEndpoint(), bucketName);
    }

    private static void initBucket() throws Exception {
        // 应用启动时检测Bucket是否存在
        boolean found = doesBucketExist(bucketName);
        // 如果Bucket不存在,则创建Bucket
        if (!found) {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            log.info("成功创建 Bucket [{}]", bucketName);
        }
    }

    /* ------------------------------------> 快速启动  <------------------------------------------------ */

    /**
     * 上传文件
     *
     * @param is          输入流
     * @param object      对象(文件)名
     * @param contentType 文件类型
     */
    public static void putObject(InputStream is, String object, String contentType) throws Exception {
        long start = System.currentTimeMillis();
        minioClient.putObject(PutObjectArgs.builder()
                .bucket(bucketName)
                .object(object)
                .contentType(contentType)
                .stream(is, -1, 1024 * 1024 * 10) // 不得小于 5 Mib
                .build());
        log.info("成功上传文件至云端 [{}],耗时 [{} ms]", object, System.currentTimeMillis() - start);
    }

    /**
     * 获取文件流
     *
     * @param object 对象(文件)名
     * @return 文件流
     */
    public static GetObjectResponse getObject(String object) throws Exception {
        long start = System.currentTimeMillis();
        GetObjectResponse response = minioClient.getObject(GetObjectArgs.builder()
                .bucket(bucketName)
                .object(object)
                .build());
        log.info("成功获取 Object [{}],耗时 [{} ms]", object, System.currentTimeMillis() - start);
        return response;
    }

    /**
     * 删除对象(文件)
     *
     * @param object 对象(文件名)
     */
    public static void removeObject(String object) throws Exception {
        minioClient.removeObject(RemoveObjectArgs.builder()
                .bucket(bucketName)
                .object(object)
                .build());
        log.info("成功删除 Object [{}]", object);
    }
    /* ------------------------------------> 快速启动 end  <------------------------------------------------ */


    /* ------------------------------------> 桶相关的操作  <------------------------------------------------ */

    /**
     * 创建桶
     *
     * @param bucketName bucket名称
     * @throws MinioException minio异常
     */
    public static void createBucket(String bucketName) throws MinioException {
        try {
            if (!minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build())) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            }
        } catch (Exception e) {
            log.error("minio 异常 {} ", e);
            throw new MinioException("create Bucket error!");
        }
    }

    /**
     * 判断桶是否存在
     *
     * @param bucketName 存储桶
     * @return true:存在
     */
    public static boolean doesBucketExist(String bucketName) throws MinioException {
        try {
            return minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        } catch (Exception e) {
            log.error("minio 异常 {} ", e);
            throw new MinioException("does Bucket Exist error!");
        }
    }

    /**
     * 获取桶策略
     *
     * @param bucketName bucket名称
     * @return {@link String}
     * @throws MinioException s3minio异常
     */
    public static String getBucketPolicy(String bucketName) throws MinioException {
        try {
            return minioClient.getBucketPolicy(GetBucketPolicyArgs.builder().bucket(bucketName).build());
        } catch (Exception e) {
            log.error("minio 异常 {} ", e);
            throw new MinioException("get Bucket Policy error!!");
        }
    }

    /**
     * 获取所有桶
     *
     * @return {@link List}<{@link Bucket}>
     * @throws MinioException s3minio异常
     */
    public static List<Bucket> getAllBuckets() throws MinioException {
        try {
            return minioClient.listBuckets();
        } catch (Exception e) {
            log.error("minio 异常 {} ", e);
            throw new MinioException("get All Buckets error");
        }
    }

    /**
     * 获取桶信息
     *
     * @param bucketName bucket名称
     * @return {@link Optional}<{@link Bucket}>
     * @throws MinioException s3minio异常
     */
    public static Optional<Bucket> getBucketInfo(String bucketName) throws MinioException {
        try {
            return getAllBuckets().stream().filter(b -> b.name().equals(bucketName)).findFirst();
        } catch (Exception e) {
            log.error("minio 异常 {} ", e);
            throw new MinioException("get Buckets Info error");
        }
    }

    /**
     * 删除桶
     *
     * @param bucketName bucket名称
     * @throws MinioException s3minio异常
     */
    public static void removeBucket(String bucketName) throws MinioException {
        try {
            minioClient.removeBucket(RemoveBucketArgs.builder().bucket(bucketName).build());
        } catch (Exception e) {
            log.error("minio 异常 {} ", e);
            throw new MinioException("remove Bucket error!!");
        }
    }


    /* ------------------------------------> 桶相关的操作 end <------------------------------------------------ */


    /* ------------------------------------> 文件管理相关 start  <------------------------------------------------ */


    /**
     * 判断文件夹是否存在
     *
     * @param bucketName 存储桶
     * @param folderName 文件夹名称(去掉/)
     * @return true:存在
     */
    public static boolean folderExist(String bucketName, String folderName) throws MinioException {
        boolean exist = false;
        try {
            Iterable<Result<Item>> results = minioClient.listObjects(
                    ListObjectsArgs.builder().bucket(bucketName).prefix(folderName).recursive(false).build());
            for (Result<Item> result : results) {
                Item item = result.get();
                if (item.isDir() && folderName.equals(item.objectName())) {
                    exist = true;
                }
            }
        } catch (Exception e) {
            log.error("minio 异常 {} ", e);
            throw new MinioException("folderExist error!");
        }
        return exist;
    }

    /**
     * 判断对象是否存在
     *
     * @param bucketName bucket名称
     * @param objectName 对象名称
     * @return boolean
     */
    public static boolean objectExist(String bucketName, String objectName) {
        boolean exist = true;
        try {
            minioClient.statObject(StatObjectArgs.builder().bucket(bucketName).object(objectName).build());
        } catch (Exception e) {
            exist = false;
        }
        return exist;
    }


    /**
     * 获取文件外链
     *
     * @param bucketName bucket名称
     * @param objectName 对象名称
     * @param expires    过期时间 秒
     * @return {@link String}
     * @throws MinioException s3minio异常
     */
    public static String getObjectUrl(String bucketName, String objectName, Integer expires) throws MinioException {
        try {
            return minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs
                    .builder().bucket(bucketName).object(objectName).expiry(expires).method(Method.GET).build());
        } catch (Exception e) {
            log.error("minio 异常 {} ", e);
            throw new MinioException("获取文件外链异常");
        }
    }

    /**
     * 获取文件外链(1天过期
     *
     * @param bucketName bucket名称
     * @param objectName 对象名称
     * @return {@link String}
     * @throws MinioException s3minio异常
     */
    public static String getObjectUrl(String bucketName, String objectName) throws MinioException {
        try {
            return minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs
                    .builder().bucket(bucketName).object(objectName).expiry(24 * 60 * 60).method(Method.GET).build());
        } catch (Exception e) {
            log.error("minio 异常 {} ", e);
            throw new MinioException("获取文件外链异常");
        }
    }


    /**
     * 获取对象
     *
     * @param bucketName bucket名称
     * @param objectName 对象名称
     * @return {@link GetObjectResponse} 文件流
     * @throws MinioException s3minio异常
     */
    public static GetObjectResponse getObject(String bucketName, String objectName) throws MinioException {
        try {
            return minioClient.getObject(GetObjectArgs.builder()
                    .bucket(bucketName)
                    .object(objectName)
                    .build());
        } catch (Exception e) {
            log.error("minio 异常 {} ", e);
            throw new MinioException("获取对象异常");
        }
    }

    /**
     * 获取对象信息
     *
     * @param bucketName bucket名称
     * @param objectName 对象名称
     * @return {@link StatObjectResponse}
     * @throws MinioException s3minio异常
     */
    public static StatObjectResponse getObjectInfo(String bucketName, String objectName) throws MinioException {
        try {
            return minioClient.statObject(
                    StatObjectArgs.builder().bucket(bucketName).object(objectName).build());
        } catch (Exception e) {
            log.error("minio 异常 {} ", e);
            throw new MinioException("获取对象信息异常");
        }
    }


    /**
     * 获取对象 (断点下载)
     *
     * @param bucketName bucket名称
     * @param objectName 对象名称
     * @param offset     起始字节位置
     * @param length     读取长度
     * @return {@link GetObjectResponse}
     * @throws Exception 异常
     */
    public static GetObjectResponse getObject(String bucketName, String objectName, long offset, long length) throws MinioException {
        try {
            return minioClient.getObject(
                    GetObjectArgs.builder().bucket(bucketName).object(objectName).offset(offset).length(length).build());
        } catch (Exception e) {
            log.error("minio 异常 {} ", e);
            throw new MinioException("断点下载异常");
        }
    }

    /**
     * 通过MultipartFile上传文件
     *
     * @param bucketName 存储桶
     * @param file       文件
     * @param objectName 对象名
     */
    public static ObjectWriteResponse putObject(String bucketName, MultipartFile file, String objectName, String contentType) throws MinioException {
        try (InputStream inputStream = file.getInputStream()) {
            return minioClient.putObject(
                    PutObjectArgs.builder().bucket(bucketName).object(objectName).contentType(contentType)
                            .stream(inputStream, inputStream.available(), -1).build());
        } catch (Exception e) {
            log.error("minio 异常 {} ", e);
            throw new MinioException("文件上传异常");
        }
    }

    /**
     * 上传本地文件
     *
     * @param bucketName 存储桶
     * @param objectName 对象名称
     * @param fileName   本地文件路径
     */
    public static ObjectWriteResponse putObject(String bucketName, String objectName, String fileName) throws MinioException {
        try {
            return minioClient.uploadObject(UploadObjectArgs.builder()
                    .bucket(bucketName).object(objectName).filename(fileName).build());
        } catch (Exception e) {
            log.error("minio 异常 {} ", e);
            throw new MinioException("上传本地文件异常");
        }
    }

    /**
     * 通过流上传文件
     *
     * @param bucketName  存储桶
     * @param objectName  文件对象
     * @param inputStream 文件流
     */
    public static ObjectWriteResponse putObjectByStream(String bucketName, String objectName, InputStream inputStream) throws MinioException {
        try {
            return minioClient.putObject(
                    PutObjectArgs.builder().bucket(bucketName).object(objectName).stream(inputStream, inputStream.available(), -1)
                            .build());
        } catch (Exception e) {
            log.error("minio 异常 {} ", e);
            throw new MinioException("通过流上传文件异常");
        }
    }

    /**
     * 创建文件夹或目录
     *
     * @param bucketName 存储桶
     * @param objectName 目录路径
     */
    public static ObjectWriteResponse createFolder(String bucketName, String objectName) throws MinioException {
        try {
            return minioClient.putObject(
                    PutObjectArgs.builder().bucket(bucketName).object(objectName).stream(
                            new ByteArrayInputStream(new byte[]{}), 0, -1)
                            .build());
        } catch (Exception e) {
            log.error("minio 异常 {} ", e);
            throw new MinioException("文件夹创建异常");
        }
    }

    /**
     * 拷贝文件
     *
     * @param bucketName    存储桶
     * @param objectName    文件名
     * @param srcBucketName 目标存储桶
     * @param srcObjectName 目标文件名
     */
    public static ObjectWriteResponse copyObject(String bucketName, String objectName, String srcBucketName, String srcObjectName) throws MinioException {
        try {
            return minioClient.copyObject(
                    CopyObjectArgs.builder()
                            .source(CopySource.builder().bucket(bucketName).object(objectName).build())
                            .bucket(srcBucketName)
                            .object(srcObjectName)
                            .build());
        } catch (Exception e) {
            log.error("minio 异常 {} ", e);
            throw new MinioException("拷贝文件 异常");
        }
    }

    /**
     * 删除文件
     *
     * @param bucketName 存储桶
     * @param objectName 文件名称
     */
    public static void removeObject(String bucketName, String objectName) throws MinioException {
        try {
            minioClient.removeObject(
                    RemoveObjectArgs.builder()
                            .bucket(bucketName)
                            .object(objectName)
                            .build());
        } catch (Exception e) {
            log.error("minio 异常 {} ", e);
            throw new MinioException("删除文件 异常");
        }
    }


    /**
     * 批量删除对象
     *
     * @param bucketName  bucket名称
     * @param objectsName 对象名字
     * @return {@link Iterable}<{@link Result}<{@link DeleteError}>>
     * @throws MinioException s3minio异常
     */
    public static Iterable<Result<DeleteError>> removeObjects(String bucketName, List<String> objectsName) throws MinioException {
        try {
            Iterable<Result<DeleteError>> results = minioClient.removeObjects(RemoveObjectsArgs.builder().bucket(bucketName)
                    .objects(objectsName.stream().map(DeleteObject::new).collect(Collectors.toList())).build());
            return results;
        } catch (Exception e) {
            log.error("minio 异常 {} ", e);
            throw new MinioException("批量删除对象 异常");
        }
    }

    /**
     * 批量删除对象2
     *
     * @param bucketName bucket名称
     * @param objectName 对象名字
     * @return {@link Iterable}<{@link Result}<{@link DeleteError}>>
     * @throws MinioException s3minio异常
     */
    public static Iterable<Result<DeleteError>> removeObjects(String bucketName, String... objectName) throws MinioException {
        try {
            Iterable<Result<DeleteError>> results = minioClient.removeObjects(RemoveObjectsArgs.builder().bucket(bucketName)
                    .objects(Arrays.stream(objectName).map(DeleteObject::new).collect(Collectors.toList())).build());
            return results;
        } catch (Exception e) {
            log.error("minio 异常 {} ", e);
            throw new MinioException("批量删除对象 异常");
        }
    }


    /**
     * 获取文件路径的 可访问链接
     */
    public static String getAvailableFileUrl(String objectName) {
        if (CN.isEmpty(objectName) || objectName.startsWith("http"))
            return objectName;
        String cc;
        try {
            RedisUtil redisUtil = SpringContextUtils.getBean(RedisUtil.class);
            String redisKey = "minio_" + objectName;
            boolean hasRedisUtil = redisUtil != null;
            if (hasRedisUtil && redisUtil.hasKey(redisKey)) {
                return redisUtil.getStr(redisKey);
            }
            int expires = 60 * 60 * 24 * 7 - 100;
            cc = getObjectUrl(bucketName, objectName, expires);
            if (hasRedisUtil) {
                redisUtil.set(redisKey, cc, expires);
            }
        } catch (Exception e) {
            String str = DateUtils.getNowStrForLogPre() + " 【getAvailableFileUrl 获取文件路径的 可访问链接 异常】 " + e.getMessage();
            System.out.println(str);
            log.error(str, e);
            cc = objectName;
        }
        return cc;
    }

    @Data
    @NoArgsConstructor
    @Configuration
    @Component
    @ConfigurationProperties(prefix = "j****g.minio")
    public static class MinIoConfig {
        private String endpoint;
        private String accessKey;
        private String secretKey;
        private String bucketName;

        public MinIoConfig(String endpoint, String accessKey, String secretKey, String bucketName) {
            this.endpoint = endpoint;
            this.accessKey = accessKey;
            this.secretKey = secretKey;
            this.bucketName = bucketName;
        }
    }
}

标签:调用,java,String,objectName,param,bucketName,MinioException,throws,MinIO
From: https://www.cnblogs.com/kikyoqiang/p/18184414

相关文章

  • Json生成Java实体类工具
    1,贴入json内容,Javabean的类名、包名即可自动生成JavaBean代码,并可以直接打包下载源码2,支持将任意复杂/简单格式的Json字符串生成Javabean实体类3,提供Json格式错误提示,不会格式化不符合规范的Json字符串,确保了Javabean实体类的准确性4,如果你的Json字段包含系统关键字,又不......
  • Camunda JavaDelegate另一种实现
    lambada实现@ConfigurationpublicclassCommonDelegate{@Bean("test")JavaDelegatetestDelegate(){returnexecution->{System.out.println("test>>>>>");Map<String,Strin......
  • Java学设计模式之备忘录模式
    一、备忘录模式概念1.1什么是备忘录模式备忘录模式是一种行为型设计模式,它允许在不破坏封装性的前提下捕获和恢复对象的内部状态。这种模式通常用于需要实现撤销操作或者历史记录功能的场景。结构备忘录模式通常包含以下几个要素:Originator(发起人):定义了一个方法用于创建......
  • Java面试题:@PostConstruct、init-method和afterPropertiesSet执行顺序?
    在Spring框架中,@PostConstruct注解、init-method属性、以及afterPropertiesSet()方法通常用于初始化Bean的逻辑。它们都提供了在Bean创建和初始化完成后执行的方法,但执行顺序有所不同。想要知道@PostConstruct、init-method、afterPropertiesSet()的执行顺序,只要搞明白它们各自在......
  • Java学设计模式之中介者模式
    一、中介者模式概念1.1什么是中介者模式中介者模式是一种行为型设计模式,它通过将对象之间的交互行为集中到一个中介者对象中来解耦对象之间的关联。这种模式被用来减少对象之间的直接通信,从而降低了系统的耦合度,使得系统易于维护和扩展。结构中介者模式通常包含以下几个要素:......
  • Java 判断是否为工作时间
    /***判断是否为工作时间(上午:7:30-11:30下午:13:30-17:20)*@return*/publicstaticbooleanisWithinWorkingHours(){LocalTimecurrentTime=LocalTime.now();//LocalTimecurrentTime=LocalTime.parse("17:19:59");......
  • 蚂蚁面试:DDD外部接口调用,应该放在哪一层?
    文章很长,且持续更新,建议收藏起来,慢慢读!疯狂创客圈总目录博客园版为您奉上珍贵的学习资源:免费赠送:《尼恩Java面试宝典》持续更新+史上最全+面试必备2000页+面试必备+大厂必备+涨薪必备免费赠送:《尼恩技术圣经+高并发系列PDF》,帮你实现技术自由,完成职业升级,薪......
  • 操作系统线程和Java线程的状态
    操作系统线程和Java线程的状态  一、操作系统线程的状态  操作系统的线程主要有以下三个状态  1. 就绪状态(ready):线程正在等待使用CPU,经调度程序调用之后进入running状态。  2.执行状态(running):线程正在使用CPU。  3.等待状态(waiting):线程经过等......
  • 【java】ArrayList和LinkedList的区别
    一、ArrayList和LinkedList的相同点ArrayList和LinkedList都是实现了List接口的容器类,用于存储一系列的对象引用,他们都可以对元素的增删改查进行操作。ArrayList、LinkedList、Vector和Stack是List的四个实现类,List是一个接口,它继承与Collection接口,代表有序的队列。其中Vector......
  • Java学设计模式之享元模式
    一、享元模式概念1.1什么是享元模式享元模式是一种结构型设计模式,旨在通过共享对象来最大程度地减少内存使用和提高性能。在享元模式中,对象被设计成可共享的,以便在需要时能够被多个不同的上下文使用。结构享元模式通常包含以下几个要素:Flyweight(享元):定义了共享对象的接口......