JAVA-MINIO

依赖

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

对应版本

在这里插入图片描述

配置工具类

package com.github.devcude.comp.plazamall.coreservice.configuration.core;

import com.github.devcude.comp.plazamall.coreservice.util.core.DateFormUtils;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.Result;
import io.minio.SetBucketPolicyArgs;
import io.minio.errors.MinioException;
import io.minio.messages.Bucket;
import io.minio.messages.Item;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

@Component
@Slf4j
public class MinioConfig implements InitializingBean {
    @Value(value = "${minio.bucket}")
    private String bucket;
    @Value(value = "${minio.host}")
    private String host;
    @Value(value = "${minio.accessKey}")
    private String accessKey;
    @Value(value = "${minio.secretKey}")
    private String secretKey;
    private MinioClient minioClient;



    @Override
    public void afterPropertiesSet() throws Exception {
        //Assert.hasText(url, "Minio url 为空");
        Assert.hasText(accessKey, "Minio accessKey为空");
        Assert.hasText(secretKey, "Minio secretKey为空");
        this.minioClient = new MinioClient(this.host, this.accessKey, this.secretKey);
    }


    // 创建桶并设置公共访问权限
    public void createBucketWithPublicAccess(String bucket) {
        try {
            // 检查桶是否已存在,如果不存在则创建
            if (!minioClient.bucketExists(bucket)) {
                minioClient.makeBucket(bucket);
                System.out.println("Bucket created: " + bucket);
            } else {
                System.out.println("Bucket already exists: " + bucket);
            }


            // 设置桶的访问权限为 public-read
            String policyJson = "{\n" +
                    "  \"Version\": \"2012-10-17\",\n" +
                    "  \"Statement\": [\n" +
                    "    {\n" +
                    "      \"Sid\": \"PublicReadGetObject\",\n" +
                    "      \"Effect\": \"Allow\",\n" +
                    "      \"Principal\": \"*\",\n" +
                    "      \"Action\": \"s3:GetObject\",\n" +
                    "      \"Resource\": \"arn:aws:s3:::" + bucket + "/*\"\n" +
                    "    }\n" +
                    "  ]\n" +
                    "}";


            SetBucketPolicyArgs policyArgs = SetBucketPolicyArgs.builder()
                    .bucket(bucket)
                    .config(policyJson) // 公共只读权限
                    .build();
            minioClient.setBucketPolicy(policyArgs);
            log.info("桶 {} 设置为 public-read 权限!", bucket);


            System.out.println("Bucket access policy set to public-read");
        } catch (MinioException e) {
            System.err.println("Minio exception: " + e.getMessage());
            e.printStackTrace();
        } catch (Exception e) {
            System.err.println("Error: " + e.getMessage());
            e.printStackTrace();
        }
    }


    /**
     * 上传
     */
    public String putObject(MultipartFile file) throws Exception {
        try {
            System.out.println("host=" + host);
            System.out.println("accessKey=" + accessKey);
            System.out.println("secretKey=" + secretKey);
            //log.info("host=", host);
            //log.info("accessKey=", accessKey);
            //log.info("secretKey=", secretKey);

            String bucket = findAvailableBucket();

            //MultipartFile转InputStream
            byte[] byteArr = file.getBytes();
            InputStream inputStream = new ByteArrayInputStream(byteArr);

            //获取文件名称
            String filename = file.getOriginalFilename();
            String prefix = filename.substring(filename.lastIndexOf(".") + 1);//后缀
            //根据当前时间生成文件夹
            Calendar calendar = Calendar.getInstance();
            Date time = calendar.getTime();
            // 2. 格式化系统时间--- 这里的时间格式可以根据自己的需要进行改变
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            String buckfilename = format.format(time);

            String uuid = UUID.randomUUID().toString().replace("-", "");//customer_YYYYMMDDHHMM
            String fileName = buckfilename + "/" + uuid + "." + prefix; //文件全路径

            PutObjectArgs objectArgs = PutObjectArgs.builder().bucket(bucket).object(fileName)
                    .stream(inputStream, file.getSize(), -1).contentType(file.getContentType()).build();
            //文件名称相同会覆盖
            minioClient.putObject(objectArgs);

            // 获取文件访问URL
            boolean flag = bucketExists(bucket);
            String url = "";
            if (flag) {
                url = minioClient.getObjectUrl(bucket, fileName);
            }
            log.info("文件url:{}", url);
            return url;
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
        //return "";
    }

    ///**
    // * 文件下载
    // */
    //public void download(String fileName, HttpServletResponse response) {
    //    // 从链接中得到文件名
    //    InputStream inputStream;
    //    try {
    //        MinioClient minioClient = new MinioClient(host, accessKey, secretKey);
    //        ObjectStat stat = minioClient.statObject(bucket, fileName);
    //        inputStream = minioClient.getObject(bucket, fileName);
    //        response.setContentType(stat.contentType());
    //        response.setCharacterEncoding("UTF-8");
    //        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
    //        byte[] buffer = new byte[1024];
    //        int length;
    //        while ((length = inputStream.read(buffer)) > 0) {
    //            response.getOutputStream().write(buffer, 0, length);
    //        }
    //        inputStream.close();
    //    } catch (Exception e) {
    //        e.printStackTrace();
    //        System.out.println("有异常:" + e);
    //    }
    //}

    /**
     * 列出所有存储桶名称
     *
     * @return
     * @throws Exception
     */
    public List<String> listBucketNames()
            throws Exception {
        List<Bucket> bucketList = listBuckets();
        List<String> bucketListName = new ArrayList<>();
        for (Bucket bucket : bucketList) {
            bucketListName.add(bucket.name());
        }
        return bucketListName;
    }

    /**
     * 查找所有桶,返回第一个文件数未超过 48000 个文件的桶
     * 一个 bucket 最多存放 48000 个文件
     */
    private String findAvailableBucket() throws Exception {
        List<String> bucketNames = listBucketNames();
        String resBucketName = null;
        for (String bucketName : bucketNames) {
            // 获取桶中的文件数量
            long fileCount = getBucketFileCount(bucketName);
            log.info("桶:" + bucketName + "-" + "文件数:" + fileCount);

            // 查找文件数没有超过 48000 个的桶
            if (fileCount < 48000) {
                resBucketName = bucketName;
                break;
            }
        }

        if (StringUtils.isEmpty(resBucketName)) {
            //创建新桶
            String newBucketName = "renrenxueoss-" + DateFormUtils.dateFormat(new Date(), "yyyyMMddHHmmss");
            createBucketWithPublicAccess(newBucketName);
            log.info("上个桶文件数已满,创建新桶:{}",newBucketName);
            return newBucketName;
        }

        return resBucketName;
    }

    /**
     * 获取桶中的文件数量
     */
    private long getBucketFileCount(String bucketName) throws Exception {
        long fileCount = 0;
        if (bucketExists(bucketName)) {
            Iterable<Result<Item>> objects = listObjects(bucketName);
            for (Result<Item> result : objects) {
                fileCount++;
            }
        }

        return fileCount;
    }


    /**
     * 查看所有桶
     *
     * @return
     * @throws Exception
     */
    public List<Bucket> listBuckets()
            throws Exception {
        return minioClient.listBuckets();
    }

    /**
     * 检查存储桶是否存在
     *
     * @param bucketName
     * @return
     * @throws Exception
     */
    public boolean bucketExists(String bucketName) throws Exception {
        boolean flag = minioClient.bucketExists(bucketName);
        if (flag) {
            return true;
        }
        return false;
    }

    /**
     * 创建存储桶
     *
     * @param bucketName
     * @return
     * @throws Exception
     */
    public boolean makeBucket(String bucketName)
            throws Exception {
        boolean flag = bucketExists(bucketName);
        if (!flag) {
            minioClient.makeBucket(bucketName);
            return true;
        } else {
            return false;
        }
    }

    /**
     * 删除桶
     *
     * @param bucketName
     * @return
     * @throws Exception
     */
    public boolean removeBucket(String bucketName)
            throws Exception {
        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(bucketName);
            flag = bucketExists(bucketName);
            if (!flag) {
                return true;
            }
        }
        return false;
    }

    /**
     * 列出存储桶中的所有对象
     *
     * @param bucketName 存储桶名称
     * @return
     * @throws Exception
     */
    public Iterable<Result<Item>> listObjects(String bucketName) throws Exception {
        boolean flag = bucketExists(bucketName);
        if (flag) {
            return minioClient.listObjects(bucketName);
        }
        return null;
    }

    /**
     * 列出存储桶中的所有对象名称
     *
     * @param bucketName 存储桶名称
     * @return
     * @throws Exception
     */
    public List<String> listObjectNames(String bucketName) throws Exception {
        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;
    }

    /**
     * 删除一个对象
     *
     * @param bucketName 存储桶名称
     * @param objectName 存储桶里的对象名称
     * @throws Exception
     */
    public boolean removeObject(String bucketName, String objectName) throws Exception {
        boolean flag = bucketExists(bucketName);
        if (flag) {
            List<String> objectList = listObjectNames(bucketName);
            for (String s : objectList) {
                if (s.equals(objectName)) {
                    minioClient.removeObject(bucketName, objectName);
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 文件访问路径
     *
     * @param bucketName 存储桶名称
     * @param objectName 存储桶里的对象名称
     * @return
     * @throws Exception
     */
    public String getObjectUrl(String bucketName, String objectName) throws Exception {
        boolean flag = bucketExists(bucketName);
        String url = "";
        if (flag) {
            url = minioClient.getObjectUrl(bucketName, objectName);
        }
        return url;
    }
}

配置

#minio配置
minio.user=minio_Jk****
minio.pwd=minio_fZ****
minio.accessKey=xRJAmMi5azFDWp63****
minio.secretKey=D0iyW73vOigXeay4sOVXuxrueb90ITpC8JAh****
minio.bucket=plaza
minio.host=https://ylioss.****.com
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值