Tencent boss teaches you how to integrate Minio easily with SpringBoot

This article mainly introduces how to easily integrate Minio with SpringBoot to help you better understand and use the springboot framework. Interested friends can learn about it.

Using Spring Boot can be very convenient and fast to build projects, so that we don't need to care about compatibility between frameworks, applicable versions and other issues. We want to use anything, just add a configuration.

Tip: The following is the content of this article. The following cases are for reference.
1. Technical introduction
1. What is Minio?
MinIO is an object storage service based on the Apache License v2.0 open source agreement. It is compatible with the Amazon S3 cloud storage service interface, and is very suitable for storing large-capacity unstructured data, such as pictures, videos, log files, backup data, and container/virtual machine images. An object file can be of any size, from several kb to the maximum 5T .

2. Use steps
1. Import the maven library
code as follows (example):

<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. Package Minio
IFile class:

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 interface class:

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 interface implementation class:

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 configuration class:

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. The configuration file
code is as follows (example):

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. The unit test
test code is as follows (example):

`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](http://ip:9000/) 登录控制台可查看上传的文件`

`}`

`@Test`

`@Override`

`public` `void` `test() {
    
    `

`System.out.println(``"---minio 测试---"``);`

`}`

`}`

Does the summary
feel simple? Follow me and take you to reveal more Minio advanced usage source code address: Click here to view the source code.

The above is the detailed content to teach you how to integrate Minio easily with SpringBoot. For more information about SpringBoot integration with Minio, please follow the editor

Guess you like

Origin blog.csdn.net/dcj19980805/article/details/115323191