【springboot整合系列】MinIO

SpringBoot整合MinIO

1.MinIO简介

就是一个文件服务,官网上说是世界上最快的对象存储。其开源协议是AGPLv3。也就是说,商用要收费,个人若将MinIO用在开源项目上是不收费的。

2.MinIO部署

MinIO有多种部署方式,我最喜欢的还是docker部署,简单又方便。

 docker pull minio/minio
docker run -d -p 9000:9000 -p 9091:9091 --name=minio --restart=always -e "MINIO_ACCESS_KEY=admin" -e "MINIO_SECRET_KEY=admin123" -v /Users/yangnanfeng/Documents/temp/upload/data:/data -v /Users/yangnanfeng/Documents/temp/upload/data:/root/.minio  minio/minio server /data --console-address ":9091" --address ":9000"

两个 -v 要映射到咱们本地文件上,当然,你甚至可以不写。
两个 -e 对应用户名【admin】和密码 【admin123】

安装完毕后我们来验证一下。
①登录MinIO管理网页。账号 admin 密码 admin123
localhost:9000
在这里插入图片描述
②熟悉一下界面
在这里插入图片描述
③新建一个桶
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
③我们上传一个图片试试,并访问这张图片。
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

3.代码实现

如上可以手动上传下载,那么如何用Java代码进行上传下载删除呢,我们采用SpringBoot。

3.1创建一个Maven项目

<?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>
    <parent>
        <artifactId>spring-boot-parent</artifactId>
        <groupId>org.springframework.boot</groupId>
        <version>2.3.1.RELEASE</version>
    </parent>

    <groupId>org.example</groupId>
    <artifactId>SpringBoot-MinIO</artifactId>

    <dependencies>
        <!--web-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--minio-->
        <dependency>
            <groupId>io.minio</groupId>
            <artifactId>minio</artifactId>
            <version>8.4.3</version>
        </dependency>

    </dependencies>

</project>

3.2 SpringBoot启动类搞起来

package com.nanfeng.minio;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App {
    public static void main(String[] args) {
        SpringApplication.run(App.class);
    }
}

基础工作弄完了。
在这里插入图片描述

3.3创建application.properties

其实我个人更喜欢properties,因为yml有时候复制来复制去,空格就搞掉了,格式乱了有点麻烦。

## minio 的UTL
minio.endpoint=http://localhost:9000
## minio 的账号密码
minio.accessKey=admin
minio.secretKey=admin123
## minio 的自己建的桶
minio.bucket.test=test

3.4创建MinIO的配置类 并放在config包下面

package com.nanfeng.minio.config;

import io.minio.MinioClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MinioConfig {

    //读取参数

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

    @Bean
    public MinioClient minioClient() {

        MinioClient minioClient =
                MinioClient.builder()
                        .endpoint(endpoint)
                        .credentials(accessKey, secretKey)
                        .build();
        return minioClient;
    }
}

实际上minioClient自带的API很丰富,到这一步就ok了。下面是锦上添花的功能。

3.5弄一个操作类,相当于一个工具包

创建一个service包

package com.nanfeng.minio.service;

import io.minio.*;
import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * minio 操作类
 */
@Service
public class MinIOService {

    // 我最喜欢用@Resource 强烈建议不要用@autowire
    @Resource
    private MinioClient minioClient;

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

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

    /**
     * 本地文件上传
     * @param localPath 本地路径
     * @param remotePath 远程路径
     * @return 可访问地址
     */
    public String upload(String localPath,String remotePath) throws IOException, ServerException, InsufficientDataException, ErrorResponseException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
            UploadObjectArgs uploadObjectArgs = UploadObjectArgs.builder()
                    .bucket(bucket)
                    .object(localPath)
                    .filename(remotePath)
                    .build();
            minioClient.uploadObject(uploadObjectArgs);
            return endpoint + "/" + bucket + "/" + remotePath;
    }

    /**
     * 用流上传
     * @param is 文件流
     * @param remotePath 远程路径
     * @return 可访问地址
     */
    public String upload(InputStream is, String remotePath) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        PutObjectArgs args = PutObjectArgs.builder()
                .bucket(bucket)
                .object(remotePath)
                .stream(is, -1, 10485760)
                .build();
        minioClient.putObject(args);
        return endpoint + "/" + bucket + "/" + remotePath;
    }

    /**
     * 删除文件
     * @param remotePath 远程路径
     * @return
     */
    public void delete(String remotePath) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        RemoveObjectArgs args = RemoveObjectArgs.builder()
                .bucket(bucket)
                .object(remotePath)
                .build();
        minioClient.removeObject(args);
    }

    /**
     * 获取流
     * @param remotePath 远程路径
     */
    public InputStream getInputStream(String remotePath) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        GetObjectArgs args = GetObjectArgs.builder()
                .bucket(bucket)
                .object(remotePath)
                .build();
        return minioClient.getObject(args);
    }
}

3.6 写一个controller用来测试一下。

package com.nanfeng.minio.controller;


import com.nanfeng.minio.service.MinIOService;
import io.minio.errors.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;

@RestController
public class MinIOController {

    @Resource
    private MinIOService minIOService;

    @PostMapping("/upload")
    public HashMap<String, String> upload(@RequestParam(name = "file", required = false) MultipartFile file) throws IOException, ServerException, InsufficientDataException, ErrorResponseException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        String originalFilename = file.getOriginalFilename();
        assert originalFilename != null;
        String fileName = System.currentTimeMillis() + originalFilename.substring(originalFilename.lastIndexOf("."));
        String url = minIOService.upload(file.getInputStream(), fileName);
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("url",url);
        map.put("fileName",fileName);
        return map;
    }

    @GetMapping("/remove")
    public String remove(String fileName) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        minIOService.delete(fileName);
        return "success";
    }
}

4.代码写完了,postman测试一下。

①上传功能
在这里插入图片描述
返回参数fileName 为对象名、url则可直接访问。
文件上传成功
在这里插入图片描述
②删除功能
在这里插入图片描述
入参为对象名,出参success表示成功。

在这里插入图片描述

5.整个项目的git如下,开箱即用。

MinIO-Demo

  • 3
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
整合MinioSpring Boot可以通过以下几个步骤完成: 1. 首先,需要在pom.xml文件中添加Minio的依赖项。你可以使用以下代码片段添加依赖项: ```xml <dependency> <groupId>io.minio</groupId> <artifactId>minio</artifactId> <version>8.4.3</version> </dependency> ``` 2. 接下来,在application.yml(或application.properties)文件中配置Minio的连接信息。你需要提供Minio服务端的地址、访问密钥和存储桶名称。以下是一个示例: ```yaml minio: url: 129.0.0.1:9000 access-key: minioadmin secret-key: minioadmin bucket-name: ding_server ``` 3. 最后,在你的代码中使用Minio客户端库进行操作。你可以根据需要使用Minio的API来上传、下载和管理对象。以下是一个使用Minio客户端库的示例: ```java import io.minio.MinioClient; import io.minio.errors.MinioException; // 创建Minio客户端 MinioClient minioClient = new MinioClient("http://localhost:9000", "minioadmin", "minioadmin"); // 上传对象到Minio存储桶 minioClient.putObject("your-bucket-name", "your-object-name", "/path/to/your-file"); // 下载对象从Minio存储桶 minioClient.getObject("your-bucket-name", "your-object-name", "/path/to/save/downloaded-file"); // 列出Minio存储桶中的所有对象 Iterable<Result<Item>> results = minioClient.listObjects("your-bucket-name"); for (Result<Item> result : results) { Item item = result.get(); System.out.println(item.objectName()); } // 删除Minio存储桶中的对象 minioClient.removeObject("your-bucket-name", "your-object-name"); ``` 以上就是在Spring Boot整合Minio的基本步骤。你可以根据具体需求进行进一步的操作和配置。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [springboot整合minio](https://blog.csdn.net/qq_36090537/article/details/128100423)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] - *3* [SpringBoot整合Minio](https://blog.csdn.net/weixin_46573014/article/details/128476327)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值