Springboot整合Minio,2024版教程

Springboot整合Minio,2024版教程

介绍

  CSDN里面找资料真的是垃圾堆里刨食吃。优质作者和内容非常少,最近还出现了评论下方打广告的,粉丝上w,文章内容质量主打一个抄袭,乱写。真的难评价。
  我为什么写这个?是因为我看了下搜到文章,内容掐头去尾,主打一个说了好像又没说。

安装方式

  最新Minio安装

代码

   直接copy可使用。也可联系我Q:1101165230

pom

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

yml

minio:
  endpoint: http://192.168.20.18:9000 #访问地址
  username: guoshun #用户名
  password: guoshun123... #密码
  bucket: project.apply  #存储文件夹名称

config

import io.minio.MinioClient;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @version 1.0.0
 * @description minioConfig
 * @date 2024/4/4 10:44
 * @created by Guoshun
 */
@Log4j2
@Configuration
public class MinioConfig {

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

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

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

    @Bean
    public MinioClient minioClient() {
        MinioClient minioClient = MinioClient.builder()
            .endpoint(endPoint)
            .credentials(username, password)
            .build();
        log.info("minioClient initialized.");
        return minioClient;
    }

}

MinioService

	
import io.minio.*;
import io.minio.errors.*;
import io.minio.http.Method;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.TimeUnit;

/**
 * @version 1.0.0
 * @description minio启动时创建bucket
 * @date 2024/4/4 14:00
 * @created by Guoshun
 */
@Slf4j
@Component
public class MinioService {

    @Resource
    private MinioClient minioClient;

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

    /**
     * 创建bucket
     * @return Boolean true成功 false 失败
     */
    @PostConstruct
    public Boolean createBucket(){
        BucketExistsArgs bucketExistsArgs = BucketExistsArgs.builder()
            .bucket(bucketName).build();
        try {
            boolean existsFlag = minioClient.bucketExists(bucketExistsArgs);
            if(!existsFlag){
                MakeBucketArgs makeBucketArgs = MakeBucketArgs.builder().bucket(bucketName).build();
                minioClient.makeBucket(makeBucketArgs);
            }
        }catch (Exception e){
            e.printStackTrace();
            log.error("Minio的bucket初始化失败{}", bucketName);
            return false;
        }
        return true;
    }

    /**
     * 文件上传
     * @param inputStream
     * @param contentType
     * @param fileName
     * @return
     */
    public Boolean put(InputStream inputStream, String contentType, String fileName) throws IOException {
        try {
            PutObjectArgs stream = PutObjectArgs.builder()
                .object(fileName)
                .bucket(bucketName)
                .contentType(contentType)
                .stream(inputStream, inputStream.available(), -1).build();
            minioClient.putObject(stream);
            return true;
        }catch (Exception e){
            log.error("文件上传失败,文件{}", fileName);
            throw new RuntimeException(e.getMessage());
        }finally {
            if(inputStream != null){
                inputStream.close();
            }
        }
    }

    /**
     * 获取文件的url地址
     * 支持版本管理后续增加
     *
     * @param fileName
     */
    public String getDownloadUrl(String fileName) {
        GetPresignedObjectUrlArgs presignedObjectUrlArgs = GetPresignedObjectUrlArgs.builder()
            .bucket(bucketName).object(fileName).method(Method.GET).expiry(1, TimeUnit.HOURS).build();
        try {
            String downloadUrl = minioClient.getPresignedObjectUrl(presignedObjectUrlArgs);
            return downloadUrl;
        } catch (ServerException |
            InsufficientDataException | ErrorResponseException |
            IOException | NoSuchAlgorithmException | InvalidKeyException | InvalidResponseException | XmlParserException | InternalException e) {
            log.error("文件下载失败{}", fileName);
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 获取文件流
     * 后续支持写入抬头
     *
     * @param fileName
     */
    public ByteArrayOutputStream getDownloadFile(String fileName) throws IOException {
        GetObjectArgs getObjectArgs = GetObjectArgs.builder().object(fileName).bucket(bucketName).build();
        byte[] buf = new byte[1024];
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream(1024);
        try {
            GetObjectResponse downloadUrl = minioClient.getObject(getObjectArgs);
            int length = 0;
            while ((length = downloadUrl.read(buf)) > 0) {
                outputStream.write(buf, 0, length);
            }
            return outputStream;
        } catch (ServerException |
            InsufficientDataException | ErrorResponseException |
            IOException | NoSuchAlgorithmException | InvalidKeyException | InvalidResponseException | XmlParserException | InternalException e) {
            log.error("文件下载失败{}", fileName);
            throw new RuntimeException(e.getMessage());
        } finally {
            outputStream.close();
        }
    }

    /**
     * 文件删除
     *
     * @param key
     */
    public boolean deleteFile(String key) {
        RemoveObjectArgs removeObjectArgs = RemoveObjectArgs.builder().bucket(bucketName).object(key).build();
        try {
            minioClient.removeObject(removeObjectArgs);
        } catch (ServerException |
            InsufficientDataException | ErrorResponseException |
            IOException | NoSuchAlgorithmException | InvalidKeyException | InvalidResponseException | XmlParserException | InternalException e){
            log.error("文件删除失败{}", key);
            throw new RuntimeException(e.getMessage());
        }
        return true;
    }

}

推荐文章

  SpringBoot集成MinIO8.0

  • 6
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
整合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 ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值