Minio usage and integration starting dependencies

Note: Minio is an open source object storage server, equivalent to a free version of OSS. This article introduces how to deploy the Minio server in a Linux environment and use it in SpringBoot. Finally, the Minio code is packaged into a starting dependency.

Installation & Startup

Step 1: Download

First, download the server program from the official website . It is very simple. The download is just a file;

Insert image description here

It is recommended not to use the command line to directly enter download on the server wget https://dl.min.io/server/minio/release/linux-amd64/minio. The network environment is not good and it will be extremely slow;

Insert image description here

Step 2: Start

After the download is completed, it is a file without extension. Upload it to the cloud server, create a minio folder in the root directory, and put the server program into this folder;

Insert image description here

Insert image description here

Enter the following two lines of commands to start the minio server;

chmod +x minio
MINIO_ROOT_USER=admin MINIO_ROOT_PASSWORD=password ./minio server /mnt/data --console-address ":9001"
  • The first line of command: Set executable permissions for the minio file;

  • The second line of command: Set the account (admin) and password (password) of the minio server, and start it. The port is 9001;

Be careful not to have too few password digits, otherwise the startup will fail. Just use the default one;

Insert image description here

Step Three: Login Test

After the startup is completed, you can IP:端口access it through. It should be noted that if you are using a cloud server, port 9001 needs to be opened;

Insert image description here

Enter the address on the page to access the minio management platform;

Insert image description here

Step 4: Use

If you have used OSS, you will be very familiar with the operations on these interfaces;

Insert image description here

Create a bucket, set it to public, and use it later in the code;

Insert image description here

After creating the bucket, you can directly upload file resources to Minio;

Insert image description here

Code usage

Step 1: Create a project

First, create a simple SpringBoot project, adding only the following two dependencies. The pom file is as follows:

<?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>com.hzy</groupId>
    <artifactId>minio-simple</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
    </properties>

    <!--Springboot项目-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.12</version>
        <relativePath/>
    </parent>

    <dependencies>
        <!--启动类依赖-->
        <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>

Step 2: Create configuration class

Create the configuration file class required by Minio, and inject a MinioClient object into the IOC container;

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

@ConfigurationProperties(prefix = "minio")
public class MinioConfig {
    
    

    private String endpoint;
    private String bucketName;
    private String accessKey;
    private String secretKey;

    public String getEndpoint() {
    
    
        return endpoint;
    }

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

    public String getBucketName() {
    
    
        return bucketName;
    }

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

    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;
    }

    /**
     * 创建一个Minio客户端
     * @return
     */
    @Bean
    public MinioClient createMinioClient(){
    
    
        return MinioClient
                .builder()
                .endpoint(endpoint)
                .credentials(accessKey,secretKey)
                .build();
    }
}

Step 3: Create an operation class

Create a tool class for Minio operation, as follows, please refer to (http://t.csdn.cn/hHfDK) for more information:

import com.hzy.config.MinioConfig;
import io.minio.*;
import io.minio.http.Method;
import io.minio.messages.Bucket;
import io.minio.messages.DeleteObject;
import io.minio.messages.Item;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;

/**
 * MinIO工具类
 */
@Component
@EnableConfigurationProperties(MinioConfig.class)
public class MinioUtils {
    
    

    @Autowired
    private MinioClient minioClient;

    @Autowired
    private MinioConfig minIOConfig;

    /**
     * 创建基于Java端的MinioClient
     */
    public void createMinioClient() {
    
    
        if (null == minioClient) {
    
    
            minioClient = MinioClient
                    .builder()
                    .endpoint(minIOConfig.getEndpoint())
                    .credentials(minIOConfig.getAccessKey(), minIOConfig.getSecretKey())
                    .build();
            try {
    
    
                createBucket(minIOConfig.getBucketName());
            } catch (Exception e) {
    
    
                e.printStackTrace();
            }
        }
    }

    /**
     * 启动SpringBoot容器的时候初始化Bucket
     * 如果没有Bucket则创建
     *
     * @throws Exception
     */
    private void createBucket(String bucketName) throws Exception {
    
    
        if (!bucketExists(bucketName)) {
    
    
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
        }
    }

    /**
     * 判断Bucket是否存在,true:存在,false:不存在
     *
     * @return
     * @throws Exception
     */
    public boolean bucketExists(String bucketName) throws Exception {
    
    
        return minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
    }

    /**
     * 使用MultipartFile进行文件上传
     *
     * @param bucketName  存储桶
     * @param fileBytes   文件字节数组
     * @param objectName  对象名
     * @param contentType 类型
     * @return
     * @throws Exception
     */
    public ObjectWriteResponse uploadFile(String bucketName, byte[] fileBytes, String objectName,
                                          String contentType) throws Exception {
    
    

        InputStream inputStream = new ByteArrayInputStream(fileBytes);

        return minioClient.putObject(
                PutObjectArgs.builder()
                        .bucket(bucketName)
                        .object(objectName)
                        .contentType(contentType)
                        .stream(inputStream, inputStream.available(), -1)
                        .build());
    }
}

Step 4: Add configuration

Set the configuration file as follows. Note that the port connected to the Minio code side is 9000, so if you are using a cloud server, you need to open this port;

minio:
  endpoint: http://Minio服务器IP:9000
  bucketName: simple
  accessKey: admin
  secretKey: password

Step 5: Create Controller to start

Finally, create a Controller, start it, and test it;

import com.hzy.utils.MinioUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
public class MinioController {
    
    

    @Autowired
    private MinioUtils minioUtils;

    @PostMapping("upload")
    public void uploadImage(MultipartFile file){
    
    
        try {
    
    
            minioUtils.uploadFile("simple", file.getBytes(), "pic", file.getContentType());
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }
    }
}

Step Six: Upload File Test

Use Apifox, fill in the address, request method as POST, request data as Body, form, parameter name file (must be consistent with the controller layer), and select the file;

Insert image description here

After the sending is completed, check the Minio management platform and view the file;

Insert image description here

You can see that the image has been uploaded successfully;

Insert image description here

At this time, click on the picture, there is a link on the right Share, click it, and you can see the link to the picture in the pop-up window;

Insert image description here

But please note that this link is a fake link and is invalid. Only by changing this link to the following can you access the image:

http://Minio服务器IP:9000/bucket名/文件路径

Insert image description here

If after pressing Enter, there is no picture and the following information is prompted, you need检查一下你的bucket是不是public(公开的)

Insert image description here

Step 7: Optimize

We can splice this path in the code. For example, after uploading a picture, we need to store this address in the database, so we can change the code to the following:

@RestController
public class MinioController {
    
    

    @Autowired
    private MinioUtils minioUtils;

    @Autowired
    private MinioConfig minioConfig;

    @PostMapping("upload")
    public String uploadImage(MultipartFile file) {
    
    
        // 生成UUID作为文件的名称
        String fileName = UUID.randomUUID() + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf('.'));
        try {
    
    
            // 上传到Minio上
            minioUtils.uploadFile(minioConfig.getBucketName(), file.getBytes(), fileName, file.getContentType());
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }
        // 文件的路径,可存入数据库
        return minioConfig.getEndpoint() + "/" + minioConfig.getBucketName() + "/" + fileName;
    }
}

Send pictures to test;

Insert image description here

Open this link to access this image;

Insert image description here

Of course, this is still very rough. When used in projects, you need to consider image size and format verification, directory classification, image review, etc.;

Starting dependence

Step 1: Create a project

First, create another SpringBoot project to test Minio's starting dependencies. The pom file is as follows:

<?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>com.hzy</groupId>
    <artifactId>starter-simple</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
    </properties>

    <!--Springboot项目-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.12</version>
        <relativePath/>
    </parent>

    <dependencies>
        <!--启动类依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!--minio起步依赖-->
        <dependency>
            <groupId>com.hzy</groupId>
            <artifactId>minio-simple</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
    </dependencies>
</project>

Step 2: Cut the code

Cut the controller layer code and application.yml configuration in the previous Minio project, as follows:

Insert image description here

Step 3: Modify Minio dependencies

Minio is a starting dependency. In order to prevent other modules from being referenced and used, the principle is to reference other dependencies as little as possible and reduce the cost of using other modules, so some tailoring is required;

So, if you are not sure which dependencies should be removed, one of my methods is to remove the dependencies first, and then follow the prompts to add the corresponding dependencies according to the error annotation , so that you can add as few dependencies as possible.

(Remove the content of the parent tag in the Minio-simple project, the code will report an error, and add dependencies according to the prompts)

Insert image description here

Follow the prompts and add the following dependencies to the minio-simple project.

<?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>com.hzy</groupId>
    <artifactId>minio-simple</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
    </properties>

    <dependencies>
        <!--minio依赖-->
        <dependency>
            <groupId>io.minio</groupId>
            <artifactId>minio</artifactId>
            <version>8.4.3</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.3.27</version>
            <scope>compile</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot</artifactId>
            <version>2.7.12</version>
            <scope>compile</scope>
        </dependency>
    </dependencies>

</project>

After the transformation is completed, it is strongly recommended to start the starter-simple project (demo project) to test whether the function can still run smoothly;

Insert image description here


Insert image description here

Step 4: Execute the install command

In Maven in the minio-simple project, skip test, execute the install command, and install this project to the local warehouse;
Insert image description here

Execution completed;

Insert image description here

At this point, this Maven can be found in the local repository;

Insert image description here

Step 5: Test

The last step, and the most important step, is to test whether the starting dependency is successfully integrated.

First of all, the previous minio-simple project needs to be removed from the project space. Some students ignore this step. After the test is successful, they think that the startup dependency integration is completed. In fact, it is not the case. In this way, the code in the minio-simple project is still used. , instead of the jar package in the local warehouse;

Insert image description here

Confirm that the Maven coordinates of Minio's starting dependency are added to pom.xml;

Insert image description here

Startup project;

Insert image description here

Finished test;

Insert image description here

At this point, Minio's starting dependency integration is completed. In other projects in the future, you can directly introduce this dependency into the project, automatically assemble the corresponding Bean object, and use the corresponding method;

Summarize

Minio is similar to OSS, but it is open source and free, so it is recommended to use it;

Guess you like

Origin blog.csdn.net/qq_42108331/article/details/132164274