minio项目实例

简介: minio项目实例

本文已参与「新人创作礼」活动,一起开启掘金创作之路。
上篇文章写一下搭建完minio后怎么写一个java的测试工程,进行体验minio对象存储功能。

1.创建maven项目 导入pom依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>minio</artifactId>
    <version>1.0-SNAPSHOT</version>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>2021.0.1.0</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>LATEST</version>
        </dependency>
    <!-- 引入thymeleaf 做简单网页测试-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
            <version>2.6.3</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.6.3</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
            <version>1.18.22</version>
        </dependency>
    <!-- minio依赖-->
        <dependency>
            <groupId>io.minio</groupId>
            <artifactId>minio</artifactId>
            <version>7.0.1</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.6</version>
        </dependency>
        <!-- 增加nacos配置 注册中心-->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>

        <!-- 增加nacos配置 配置中心-->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
    </dependencies>

    <build>
   na     <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal><!--可以把依赖的包都打包到生成的Jar包中 -->
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

2.编写application.yml配置文件

server:
  port: 8085
spring:
  application:
    name: book-minio
  thymeleaf:
    cache: false
  servlet:
    multipart:
      max-file-size: 10MB
      max-request-size: 100MB
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848
        namespace: f5caca8a-aa97-4fed-a9b3-92691006dbff
      config:
        server-addr: localhost:8848
        namespace: f5caca8a-aa97-4fed-a9b3-92691006dbff
  config:
    import:
      - nacos:minio-config-client-dev.yaml

management:
  endpoints:
    web:
      exposure:
        include:'*'

这块用到nacos服务注册、配置中心,如果不想用可以直接将配置写在yml文件中。

nacos中minio-config-client-dev.yaml文件的详细配置

image.png
配置了搭建的minio的地址、ip、用户名、密码、文件大小限制信息

4.工程目录

image.png

MinioController

package com.ctsi.ssdx.controller;

import com.alibaba.fastjson.JSON;
import com.ctsi.ssdx.common.Res;
import com.ctsi.ssdx.config.MinioProp;
import io.minio.MinioClient;
import io.minio.ObjectStat;
import io.minio.PutObjectOptions;
import io.minio.Result;
import io.minio.messages.Item;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.*;

/**
 * @Author : lizzu
 * @create 2022/8/11 14:27
 */
@Slf4j
@RestController
public class MinioController {
    @Autowired
    private MinioClient minioClient;

    @Autowired
    private MinioProp minioProp;

    private static final String MINIO_BUCKET = "mybucket";

    @GetMapping("/list")
    public List<Object> list(ModelMap map) throws Exception {
        Iterable<Result<Item>> myObjects = minioClient.listObjects(MINIO_BUCKET);
        Iterator<Result<Item>> iterator = myObjects.iterator();
        List<Object> items = new ArrayList<>();
//        String format = "{'fileName':'%s','filePath':'%s','fileSize':'%s'}";
        String format = "{'fileName':'%s','fileSize':'%s'}";
        while (iterator.hasNext()) {
            Item item = iterator.next().get();
            items.add(JSON.parse(String.format(format,
//                    minioProp.getEndpoint()+"/"+MINIO_BUCKET+"/"+item.objectName(),
                    item.objectName(), formatFileSize(item.size()))));
        }
        return items;
    }

    @PostMapping("/upload")
    public Res upload(@RequestParam(name = "file", required = false) MultipartFile[] file) {
        Res res = new Res();
        res.setCode(500);

        if (file == null || file.length == 0) {
            res.setMessage("上传文件不能为空");
            return res;
        }

        List<String> orgfileNameList = new ArrayList<>(file.length);

        for (MultipartFile multipartFile : file) {
            String orgfileName = multipartFile.getOriginalFilename();
            orgfileNameList.add(orgfileName);

            try {
                InputStream in = multipartFile.getInputStream();
                minioClient.putObject(MINIO_BUCKET, orgfileName, in, new PutObjectOptions(in.available(), -1));
                in.close();
            } catch (Exception e) {
                log.error(e.getMessage());
                res.setMessage("上传失败");
                return res;
            }
        }

        Map<String, Object> data = new HashMap<String, Object>();
        data.put("bucketName", MINIO_BUCKET);
        data.put("fileName", orgfileNameList);
        res.setCode(200);
        res.setMessage("上传成功");
        res.setData(data);
        return res;
    }

    @RequestMapping("/download/{fileName}")
    public void download(HttpServletResponse response, @PathVariable("fileName") String fileName) {
        InputStream in = null;
        try {
            ObjectStat stat = minioClient.statObject(MINIO_BUCKET, fileName);
            response.setContentType(stat.contentType());
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));

            in = minioClient.getObject(MINIO_BUCKET, fileName);
            IOUtils.copy(in, response.getOutputStream());
        } catch (Exception e) {
            log.error(e.getMessage());
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    log.error(e.getMessage());
                }
            }
        }
    }

    @DeleteMapping("/delete/{fileName}")
    public Res delete(@PathVariable("fileName") String fileName) {
        Res res = new Res();
        res.setCode(200);
        try {
            minioClient.removeObject(MINIO_BUCKET, fileName);
        } catch (Exception e) {
            res.setCode(500);
            log.error(e.getMessage());
        }
        return res;
    }

    private static String formatFileSize(long fileS) {
        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString = "";
        String wrongSize = "0B";
        if (fileS == 0) {
            return wrongSize;
        }
        if (fileS < 1024) {
            fileSizeString = df.format((double) fileS) + " B";
        } else if (fileS < 1048576) {
            fileSizeString = df.format((double) fileS / 1024) + " KB";
        } else if (fileS < 1073741824) {
            fileSizeString = df.format((double) fileS / 1048576) + " MB";
        } else {
            fileSizeString = df.format((double) fileS / 1073741824) + " GB";
        }
        return fileSizeString;
    }
}

配置信息MinioProp


import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * @Author : lizzu
 * @create 2022/8/11 14:24
 */
@Data
//@ConfigurationProperties(prefix = "minio")
@Component
public class MinioProp {

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

    @Value("${minio.accesskey}")

    private String accesskey;

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

}

MinioConfiguration


import io.minio.MinioClient;
import io.minio.errors.InvalidEndpointException;
import io.minio.errors.InvalidPortException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Author : lizzu
 * @create 2022/8/11 14:25
 */
@Configuration
public class MinioConfiguration {
    @Autowired
    private MinioProp minioProp;

    @Bean
    public MinioClient minioClient() throws InvalidPortException, InvalidEndpointException {
        MinioClient client = new MinioClient(minioProp.getEndpoint(), minioProp.getAccesskey(), minioProp.getSecretKey());
        return client;
    }
}

简单前端测试:
image.png

image.png
附gitee源码地址 https://gitee.com/qlglg123/minio

相关文章
|
5月前
|
人工智能 运维 安全
无需Mac mini!2026年4步在阿里云构建OpenClaw(Clawdbot) AI员工,零基础也能上手
2026年,AI智能体迎来规模化落地,OpenClaw(前身为Clawdbot、Moltbot)凭借“开源免费、全场景自动化、无设备限制”的核心优势,成为个人与企业构建专属AI员工的首选框架。不同于传统聊天机器人仅能提供文本建议,OpenClaw能真正实现“指令下达→任务执行”的闭环,可自动完成邮件处理、文档生成、网页抓取、日程提醒、多平台联动等重复性工作,如同7×24小时待命的全职AI员工,彻底解放人力。
701 2
|
Python
PyCharm在用Django开发时debug模式启动失败显示can&#39;t find &#39;__main__&#39; module的解决方法
初次用Django开发web应用,在试图用Pycharm进行debug的时候,出现了一个奇怪的问题。以正常模式启动或者在terminal启动都没有问题。但是以debug模式启动时,显示`can&#39;t find &#39;__main__&#39; module”`报错。在网上找了很久都没有看到解决方法,最后在某乎上看到一篇文章,在启动时加上`--noreload`参数,既可以debug模式启动。
689 0
|
10月前
|
机器学习/深度学习 算法 Python
【分布鲁棒】基于Wasserstein距离的两阶段分布鲁棒简易模型【对偶转化】【线性决策】(Matlab代码实现)
【分布鲁棒】基于Wasserstein距离的两阶段分布鲁棒简易模型【对偶转化】【线性决策】(Matlab代码实现)
645 0
|
缓存
【已解决】npm安装依赖报错: npm ERR! cb() never called! npm ERR! This is an error with npm itself.
【已解决】npm安装依赖报错: npm ERR! cb() never called! npm ERR! This is an error with npm itself.
3942 0
|
传感器 人工智能 搜索推荐
数字孪生在医疗健康中的作用:重塑医疗体验与提升服务质量
数字孪生技术在医疗健康领域的应用正逐步展现出巨大潜力,通过构建患者的个性化数字模型,实现精准医疗、疾病预测、手术优化、设备仿真和患者管理,显著提升了医疗服务质量与患者体验。
1027 5
|
机器学习/深度学习 算法 自动驾驶
深度强化学习在大模型中的应用:现状、问题和发展
强化学习在大模型中的应用具有广泛的潜力和机会。通过使用强化学习算法,如DQN、PPO和TRPO,可以训练具有复杂决策能力的智能体,在自动驾驶、机器人控制和游戏玩家等领域取得显著成果。然而,仍然存在一些挑战,如样本效率、探索与利用平衡以及可解释性问题。未来的研究方向包括提高样本效率、改进探索策略和探索可解释的强化学习算法,以进一步推动强化学习在大模型中的应用。
3684 3
|
存储 安全 Linux
操作系统(13)-----文件管理4
操作系统(13)-----文件管理
774 0
|
前端开发 Java 关系型数据库
鲜花商城|基于Springboot实现鲜花商城系统
鲜花商城|基于Springboot实现鲜花商城系统
461 1
IDEA 导入项目后,可以Run,但是Debug按钮显示灰色,无法点击
IDEA 导入项目后,可以Run,但是Debug按钮显示灰色,无法点击
4128 1
IDEA 导入项目后,可以Run,但是Debug按钮显示灰色,无法点击
|
Cloud Native Linux 虚拟化
【云原生 | 03】裸金属架构之服务器安装VMWare ESXI虚拟化平台详细流程
虚拟化,是指通过虚拟化技术将一台计算机虚拟为多台逻辑计算机。在一台计算机上同时运行多个逻辑计算机,每个逻辑计算机可运行不同的操作系统,并且应用程序都可以在相互独立的空间内运行而互不影响,从而显著提高计算机的工作效率。...............
1517 0
【云原生 | 03】裸金属架构之服务器安装VMWare ESXI虚拟化平台详细流程