亲宝软件园·资讯

展开

SpringBoot整合Minio 手把手教你SpringBoot轻松整合Minio

何裕华 人气:0

前言

使用Spring Boot 可以非常方便、快速搭建项目,使我们不用关心框架之间的兼容性,适用版本等各种问题,我们想使用任何东西,仅仅添加一个配置就可以。

提示:以下是本篇文章正文内容,下面案例可供参考

一、技术介绍

1.Minio是什么?

MinIO 是一个基于Apache License v2.0开源协议的对象存储服务。它兼容亚马逊S3云存储服务接口,非常适合于存储大容量非结构化的数据,例如图片、视频、日志文件、备份数据和容器/虚拟机镜像等,而一个对象文件可以是任意大小,从几kb到最大5T不等。

二、使用步骤

1.引入maven库

代码如下(示例):

	 	<parent>
	    <groupId>org.springframework.boot</groupId>
	    <artifactId>spring-boot-starter-parent</artifactId>
	    <version>2.4.1</version>
	    <relativePath/>
	  </parent>
    <dependencies>
    <dependency>
      <groupId>io.minio</groupId>
      <artifactId>minio</artifactId>
      <version>8.0.3</version>
    </dependency>
  </dependencies>

2.封装Minio

IFile类:

package com.hyh.minio;

/**
 * File接口类
 *
 * @Author: heyuhua
 * @Date: 2021/1/12 10:33
 */
public interface IFile {

  /**
   * 上传
   *
   * @param filename 文件名
   */
  void upload(String filename);

  /**
   * 上传
   *
   * @param filename 文件名
   * @param object  保存对象文件名称
   */
  void upload(String filename, String object);
}





File接口类:

package com.hyh.minio.service;

import com.hyh.minio.IFile;

/**
 * File接口
 *
 * @Author: heyuhua
 * @Date: 2021/1/12 10:53
 */
public interface FileService extends IFile {

  /**
   * 上传
   *
   * @param filename 文件名称
   * @param object  保存对象文件名称
   * @param bucket  存储桶
   */
  void upload(String filename, String object, String bucket);
}






File接口实现类:

package com.hyh.minio.service.impl;

import com.hyh.minio.service.FileService;
import com.hyh.utils.common.StringUtils;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.UploadObjectArgs;
import io.minio.errors.MinioException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * 文件接口服务实现
 *
 * @Author: heyuhua
 * @Date: 2021/1/12 10:53
 */
@Service
public class FileServiceImpl implements FileService {

  /**
   * 日志
   */
  private static final Logger LOG = LoggerFactory.getLogger(FileServiceImpl.class);

  /**
   * minio 客户端
   */
  @Autowired
  private MinioClient minioClient;

  /**
   * 默认存储桶名称
   */
  @Value("${minio.bucketName:}")
  private String defaultBucketName;


  @Override
  public void upload(String filename) {
    uploadObject(filename, null, defaultBucketName);
  }

  @Override
  public void upload(String filename, String object) {
    uploadObject(filename, object, defaultBucketName);
  }


  @Override
  public void upload(String filename, String object, String bucket) {
    uploadObject(filename, object, bucket);
  }

  /**
   * 上传
   *
   * @param filename
   * @param object
   * @param bucket
   */
  private void uploadObject(String filename, String object, String bucket) {
    if (StringUtils.isAnyBlank(filename, bucket))
      return;
    try {
      //存储桶构建
      bucketBuild(bucket);
      //保存的文件名称
      object = StringUtils.isBlank(object) ? filename.substring(filename.lastIndexOf("/") > 0 ? filename.lastIndexOf("/") : filename.lastIndexOf("\\")) : object;

      minioClient.uploadObject(
          UploadObjectArgs.builder()
              .bucket(bucket)
              .object(object)
              .filename(filename)
              .build());
    } catch (MinioException | InvalidKeyException | IOException | NoSuchAlgorithmException exception) {
      LOG.error("uploadObject error", exception);
    }
  }


  /**
   * 存储桶构建
   *
   * @param bucketName
   */
  private void bucketBuild(String bucketName) {
    try {
      boolean found =
          minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
      if (!found) {
        minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
        LOG.info("Bucket " + bucketName + " make success.");
      } else {
        LOG.info("Bucket " + bucketName + " already exists.");
      }
    } catch (MinioException | InvalidKeyException | IOException | NoSuchAlgorithmException exception) {
      LOG.error("bucketBuild error", exception);
    }
  }

  public String getDefaultBucketName() {
    return defaultBucketName;
  }

  public void setDefaultBucketName(String defaultBucketName) {
    this.defaultBucketName = defaultBucketName;
  }
}






Minio配置类:

package com.hyh.minio.config;

import io.minio.MinioClient;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Author: heyuhua
 * @Date: 2021/1/12 10:42
 */
@Configuration
@ConfigurationProperties(prefix = "minio")
public class MinioConfig {

  /**
   * endPoint是一个URL,域名,IPv4或者IPv6地址
   */
  private String endpoint;

  /**
   * 端口
   */
  private int port;

  /**
   * accessKey类似于用户ID,用于唯一标识你的账户
   */
  private String accessKey;

  /**
   * secretKey是你账户的密码
   */
  private String secretKey;

  /**
   * 如果是true,则用的是https而不是http,默认值是true
   */
  private Boolean secure;

  /**
   * 默认存储桶
   */
  private String bucketName;

  /**
   * 配置目录
   */
  private String configDir;

  @Bean
  public MinioClient getMinClient() {
    return MinioClient.builder()
        .endpoint(endpoint, port, secure)//http
        .credentials(accessKey, secretKey)
        .build();
  }


  public String getEndpoint() {
    return endpoint;
  }

  public void setEndpoint(String endpoint) {
    this.endpoint = endpoint;
  }

  public String getAccessKey() {
    return accessKey;
  }

  public void setAccessKey(String accessKey) {
    this.accessKey = accessKey;
  }

  public String getSecretKey() {
    return secretKey;
  }

  public void setSecretKey(String secretKey) {
    this.secretKey = secretKey;
  }

  public Boolean getSecure() {
    return secure;
  }

  public void setSecure(Boolean secure) {
    this.secure = secure;
  }

  public String getBucketName() {
    return bucketName;
  }

  public void setBucketName(String bucketName) {
    this.bucketName = bucketName;
  }

  public String getConfigDir() {
    return configDir;
  }

  public void setConfigDir(String configDir) {
    this.configDir = configDir;
  }

  public int getPort() {
    return port;
  }

  public void setPort(int port) {
    this.port = port;
  }
}







Minio助手类封装:

package com.hyh.minio.helper;

import com.hyh.minio.service.FileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

/**
 * Minio助手
 *
 * @Author: heyuhua
 * @Date: 2021/1/12 10:54
 */
@Component
public class MinioHelper {

  /**
   * 日志
   */
  private static final Logger LOG = LoggerFactory.getLogger(MinioHelper.class);

  /**
   * 文件接口服务
   */
  @Autowired
  private FileService fileService;


  /**
   * 上传
   *
   * @param filename
   */
  public void upload(String filename) {
    Assert.notNull(filename, "filename is null.");
    fileService.upload(filename);
  }

  /**
   * 上传
   *
   * @param filename
   * @param object
   */
  public void upload(String filename, String object) {
    Assert.notNull(filename, "filename is null.");
    Assert.notNull(object, "object is null.");
    fileService.upload(filename, object);
  }

  /**
   * 上传
   *
   * @param filename
   * @param object
   * @param bucket
   */
  public void upload(String filename, String object, String bucket) {
    Assert.notNull(filename, "filename is null.");
    Assert.notNull(object, "object is null.");
    Assert.notNull(bucket, "bucket is null.");
    fileService.upload(filename, object, bucket);
  }


}







3.配置文件

代码如下(示例):

server:
 port: 8088
#minio配置
minio:
 endpoint: 39.108.49.252
 port: 9000
 accessKey: admin
 secretKey: admin123
 secure: false
 bucketName: "hyh-bucket"
 configDir: "/home/data/"

4.单元测试

测试代码如下(示例):

package com.hyh.core.test;

import com.hyh.core.test.base.HyhTest;
import com.hyh.minio.helper.MinioHelper;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * Minio Test
 *
 * @Author: heyuhua
 * @Date: 2021/1/12 11:54
 */
public class MinioTest extends HyhTest {

  @Autowired
  private MinioHelper minioHelper;

  @Test
  public void testUpload() {
    //直接指向你本地的路径测试
    String filename = "E:\\home\\static\\img\\fsPic\\0c34de99ac6b4c56812e83c4eab13a6f.jpg";
    String object = "hyh-test-name.jpg";
    String bucket = "hyh-test-bucket";
    minioHelper.upload(filename);
    minioHelper.upload(filename, object);
    minioHelper.upload(filename, object, bucket);
    //上传完后打开浏览器访问 http://ip:9000 登录控制台可查看上传的文件
  }

  @Test
  @Override
  public void test() {
    System.out.println("---minio 测试---");
  }
}

总结

是不是感觉很简单?关注我带你揭秘更多Minio高级用法 源码地址:点此查看源码.

加载全部内容

相关教程
猜你喜欢
用户评论