中间件(18) : minio

该代码示例展示了如何在Java中利用MinIO库进行文件上传、删除、列出存储桶及对象、设置公共读权限,并提供了连接MinIO服务器的配置方法。此外,还包含了错误处理和日期格式化的功能。
Seed-Coder-8B-Base

Seed-Coder-8B-Base

文本生成
Seed-Coder

Seed-Coder是一个功能强大、透明、参数高效的 8B 级开源代码模型系列,包括基础变体、指导变体和推理变体,由字节团队开源

参考 : 

        MinIO Java接口实现创建桶,设置桶策略_minio 创建bucket_Meta.Qing的博客-优快云博客 

        Java上传文件到minio_javac-coder的博客-优快云博客 

maven依赖

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

minio配置

# minio
minio.endpoint=http://192.168.1.1:8080
minio.accessKey=minio
minio.secretKey=minio123

minio管理


import io.minio.*;
import io.minio.messages.Bucket;
import io.minio.messages.Item;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;

@Service
@Slf4j
public class MinioSaveService {

    @Value("${minio.endpoint:-}")
    private String endpoint;

    @Value("${minio.accessKey:-}")
    private String accessKey;

    @Value("${minio.secretKey:-}")
    private String secretKey;

    private MinioClient minioClient;

    private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    // 创建连接
    private MinioClient getMinioClient() {
        try {
            if (minioClient != null) {
                return minioClient;
            }
            minioClient = MinioClient.builder().endpoint(endpoint).credentials(accessKey, secretKey).build();
            log.info("minio连接创建成功");
            return minioClient;
        } catch (Exception e) {
            log.error("minio连接创建失败", e);
            return null;
        }
    }

    // 所有存储桶
    public List<String> listBuckets() throws Exception {
        List<Bucket> buckets = getMinioClient().listBuckets();
        List<String> bs = new LinkedList<>();
        if (!buckets.isEmpty()) {
            buckets.forEach(b -> bs.add(b.name()));
        }
        return bs;
    }

    // 查看目录文件列表
    public List<Map<String, Object>> listObjects(String bucket, String path) throws Exception {
        Iterable<Result<Item>> results = getMinioClient().listObjects(ListObjectsArgs.builder()
                .bucket(bucket)
                .prefix(path).build());
        Iterator<Result<Item>> iterator = results.iterator();
        List<Map<String, Object>> rs = new LinkedList<>();
        while (iterator.hasNext()) {
            Result<Item> next = iterator.next();
            Item item = next.get();
            Map<String, Object> map = new HashMap<>();
            map.put("objectName", item.objectName());
            map.put("isDir", item.isDir());
            try {
                LocalDateTime localDateTime = item.lastModified().toLocalDateTime();
                Date date = Date.from(localDateTime.atZone(ZoneId.systemDefault()).plusHours(8).toInstant());
                map.put("lastModified", simpleDateFormat.format(date));
            } catch (Exception e) {
            }
            if (!item.isDir()) {
                map.put("url", endpoint + "/" + bucket + "/" + item.objectName());
            }
            rs.add(map);
        }
        return rs;
    }

    // 删除文件
    public String deleteFile(String bucket, String objectName) throws Exception {
        getMinioClient().removeObject(RemoveObjectArgs.builder()
                .bucket(bucket)
                .object(objectName)
                .build());
        return "SUCCESS";
    }

    // 上传文件 minioPath前面不带/
    public String uploadFile(MultipartFile file, String bucket, String minioPath) throws Exception {
        // 若不存在创建bucket
        if (!bucketExists(bucket)) {
            getMinioClient().makeBucket(MakeBucketArgs.builder().bucket(bucket).build());
            getMinioClient().setBucketPolicy(
                    SetBucketPolicyArgs.builder()
                            .bucket(bucket)
                            .config(getPolicy3(bucket)) // 1,2,3都可以
                            .build());
        }
        // 上传
        String objectName = minioPath + "/" + file.getOriginalFilename();
        PutObjectArgs args = PutObjectArgs.builder()
                .bucket(bucket)
                .object(objectName)
                .stream(file.getInputStream(), file.getSize(), -1)
                .contentType(file.getContentType())
                .build();
        getMinioClient().putObject(args);
        //返回上传的路径
        return getUrl(bucket, objectName);
    }

    // 获取访问URL
    public String getUrl(String bucket, String objectName) {
        return endpoint + "/" + bucket + "/" + objectName;
    }

    // 判定bucket是否存在
    public boolean bucketExists(String bucketName) throws Exception {
        return getMinioClient().bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
    }

    // 根据URL删除文件
    public Object deleteByUrl(String url) throws Exception {
        String str = url.replace(endpoint + "/", "");
        int i = str.indexOf("/");
        return deleteFile(str.substring(0, i), str.substring(i + 1));
    }

    public static void main(String[] args) {
        String url = "http://10.149.229.82:31004/tmp/2023/20210907093457.jpg";
        String str = url.replace("http://10.149.229.82:31004" + "/", "");
        int i = str.indexOf("/");
        System.out.println(str.substring(0, i));
        System.out.println(str.substring(i + 1));
    }

    // bucket公有
    public static String getPolicy3(String bucket) {
        return "{\n" +
                "    \"Version\": \"2012-10-17\",\n" +
                "    \"Statement\": [\n" +
                "        {\n" +
                "            \"Effect\": \"Allow\",\n" +
                "            \"Principal\": {\n" +
                "                \"AWS\": [\n" +
                "                    \"*\"\n" +
                "                ]\n" +
                "            },\n" +
                "            \"Action\": [\n" +
                "                \"s3:ListBucketMultipartUploads\",\n" +
                "                \"s3:GetBucketLocation\",\n" +
                "                \"s3:ListBucket\"\n" +
                "            ],\n" +
                "            \"Resource\": [\n" +
                "                \"arn:aws:s3:::" + bucket + "\"\n" +
                "            ]\n" +
                "        },\n" +
                "        {\n" +
                "            \"Effect\": \"Allow\",\n" +
                "            \"Principal\": {\n" +
                "                \"AWS\": [\n" +
                "                    \"*\"\n" +
                "                ]\n" +
                "            },\n" +
                "            \"Action\": [\n" +
                "                \"s3:ListMultipartUploadParts\",\n" +
                "                \"s3:PutObject\",\n" +
                "                \"s3:AbortMultipartUpload\",\n" +
                "                \"s3:DeleteObject\",\n" +
                "                \"s3:GetObject\"\n" +
                "            ],\n" +
                "            \"Resource\": [\n" +
                "                \"arn:aws:s3:::" + bucket + "/*\"\n" +
                "            ]\n" +
                "        }\n" +
                "    ]\n" +
                "}";
    }

    // bucket公有
    public static String getPolicy2(String bucket) {
        return "{\n" +
                "    \"Version\": \"2012-10-17\",\n" +
                "    \"Statement\": [\n" +
                "        {\n" +
                "            \"Effect\": \"Allow\",\n" +
                "            \"Principal\": {\n" +
                "                \"AWS\": [\n" +
                "                    \"*\"\n" +
                "                ]\n" +
                "            },\n" +
                "            \"Action\": [\n" +
                "                \"s3:ListBucket\",\n" +
                "                \"s3:ListBucketMultipartUploads\",\n" +
                "                \"s3:GetBucketLocation\"\n" +
                "            ],\n" +
                "            \"Resource\": [\n" +
                "                \"arn:aws:s3:::" + bucket + "\"\n" +
                "            ]\n" +
                "        },\n" +
                "        {\n" +
                "            \"Effect\": \"Allow\",\n" +
                "            \"Principal\": {\n" +
                "                \"AWS\": [\n" +
                "                    \"*\"\n" +
                "                ]\n" +
                "            },\n" +
                "            \"Action\": [\n" +
                "                \"s3:PutObject\",\n" +
                "                \"s3:AbortMultipartUpload\",\n" +
                "                \"s3:DeleteObject\",\n" +
                "                \"s3:GetObject\",\n" +
                "                \"s3:ListMultipartUploadParts\"\n" +
                "            ],\n" +
                "            \"Resource\": [\n" +
                "                \"arn:aws:s3:::" + bucket + "/*\"\n" +
                "            ]\n" +
                "        }\n" +
                "    ]\n" +
                "}";
    }

    // bucket公有
    private static String getPolicy(String bucket) {
        return "{\n" +
                "    \"Version\": \"2012-10-17\",\n" +
                "    \"Statement\": [\n" +
                "        {\n" +
                "            \"Action\": [\n" +
                "                \"s3:GetObject\"\n" +
                "            ],\n" +
                "            \"Effect\": \"Allow\",\n" +
                "            \"Principal\": {\n" +
                "                \"AWS\": [\n" +
                "                    \"*\"\n" +
                "                ]\n" +
                "            },\n" +
                "            \"Resource\": [\n" +
                "                \"arn:aws:s3:::" + bucket + "/*\"\n" +
                "            ]\n" +
                "        }\n" +
                "    ]\n" +
                "}";
    }
}

controller


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDate;

/**
 * @Author: liyue
 * @Date: 2023/04/26/13:43
 * @Description:
 */
@RestController
public class MinioController {

    @Autowired
    private MinioSaveService minioSaveService;

    @RequestMapping("/listBuckets")
    public ResultDO listBuckets() {
        try {
            return ResultDO.buildSuccessResult(minioSaveService.listBuckets());
        } catch (Exception e) {
            return ResultDO.buildFailResult("查看所有桶失败", e.getMessage());
        }
    }

    @RequestMapping("/listObjects")
    public ResultDO listObjects(String bucket, String path) {
        try {
            return ResultDO.buildSuccessResult(minioSaveService.listObjects(bucket, path));
        } catch (Exception e) {
            e.printStackTrace();
            return ResultDO.buildFailResult("查看文件列表失败", e.getMessage());
        }
    }

    @RequestMapping("/upload")
    public ResultDO upload(@RequestParam("file") MultipartFile[] files, String bucket, String minioPath) {
        try {
            String url = null;
            for (MultipartFile file : files) {
                if (!file.isEmpty()) {
                    url = minioSaveService.uploadFile(file, bucket, minioPath);
                }
            }
            return ResultDO.buildSuccessResult(url);
        } catch (Exception e) {
            return ResultDO.buildFailResult("文件上传minio失败,bucket:" + bucket + ",minioPath:" + minioPath, e.getMessage());
        }
    }

    public static void main(String[] args) {
        System.out.println(LocalDate.now().getYear());
    }

    @RequestMapping("/uploadTmp")
    public ResultDO uploadTmp(@RequestParam("file") MultipartFile[] files) {
        try {
            String url = null;
            for (MultipartFile file : files) {
                if (!file.isEmpty()) {
                    url = minioSaveService.uploadFile(file, "tmp", String.valueOf(LocalDate.now().getYear()));
                }
            }
            return ResultDO.buildSuccessResult(url);
        } catch (Exception e) {
            return ResultDO.buildFailResult("文件上传minio失败,bucket:" + "tmp" + ",minioPath:" + LocalDate.now().getYear(), e.getMessage());
        }
    }

    @RequestMapping("/delete")
    public ResultDO delete(String bucket, String objectName) {
        try {
            return ResultDO.buildSuccessResult(minioSaveService.deleteFile(bucket, objectName));
        } catch (Exception e) {
            if (e.getMessage().contains("The specified key does not exist")) {
                return ResultDO.buildFailResult("删除失败", "文件不存在");
            }
            return ResultDO.buildFailResult("minio文件删除失败,bucket:" + bucket + ",objectName:" + objectName, e.getMessage());
        }
    }

    @RequestMapping("/deleteByUrl")
    public ResultDO deleteByUrl(String url) {
        try {
            return ResultDO.buildSuccessResult(minioSaveService.deleteByUrl(url));
        } catch (Exception e) {
            if (e.getMessage().contains("The specified key does not exist")) {
                return ResultDO.buildFailResult("删除失败", "文件不存在");
            }
            return ResultDO.buildFailResult("minio文件删除失败,url:" + url, e.getMessage());
        }
    }

    @RequestMapping("/uploadModule")
    public ResultDO uploadModule(@RequestParam("file") MultipartFile[] files) {
        try {
            String url = null;
            for (MultipartFile file : files) {
                if (!file.isEmpty()) {
                    url = minioSaveService.uploadFile(file, "flm", "module-center/software-package");
                }
            }
            return ResultDO.buildSuccessResult(url);
        } catch (Exception e) {
            return ResultDO.buildFailResult("文件上传minio失败", e.getMessage());
        }
    }

}

您可能感兴趣的与本文相关的镜像

Seed-Coder-8B-Base

Seed-Coder-8B-Base

文本生成
Seed-Coder

Seed-Coder是一个功能强大、透明、参数高效的 8B 级开源代码模型系列,包括基础变体、指导变体和推理变体,由字节团队开源

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值