MinIO使用指南

MinIO 使用指南

官网地址:https://min.io/docs/minio/linux/index.html

安装

下载发行包

新版本的管理员权限需要付费 使用老版本进行开发

下载地址:https://dl.min.io/server/minio/release/linux-amd64/archive/minio-20250422221226.0.0-1.x86_64.rpm

上传发行包

本手册上传目录为 /home

利用远程连接工具将发行包上传至 linux 服务器

安装发行包

切换到发行包所在的目录

yum localinstall minio-20250422221226.0.0-1.x86_64.rpm

创建 systemed 服务文件

vim /usr/lib/systemd/system/minio.service

文件内容:

[Unit]
Description=MinIO
Documentation=https://docs.min.io
Wants=network-online.target
After=network-online.target
AssertFileIsExecutable=/usr/local/bin/minio

[Service]
User=minio-user
Group=minio-user

EnvironmentFile=/etc/default/minio
ExecStart=/usr/local/bin/minio server $MINIO_OPTS $MINIO_VOLUMES

# Specifies the maximum file descriptor number that can be opened by this process
LimitNOFILE=65536

# Turn-off memory accounting by systemd, which is buggy.
MemoryAccounting=no

# Specifies the maximum number of threads this process can create
TasksMax=infinity

# Disable timeout logic and wait until process is stopped
TimeoutSec=infinity

# Disable killing of MinIO by the kernel's OOM killer
OOMScoreAdjust=-1000

SendSIGKILL=no

[Install]
WantedBy=multi-user.target

# Built for ${project.name}-${project.version} (${project.name})

创建环境变量文件

vim /etc/default/minio
# MINIO_ROOT_USER and MINIO_ROOT_PASSWORD sets the root account for the MinIO server.
# This user has unrestricted permissions to perform S3 and administrative API operations on any resource in the deployment.
# Omit to use the default values 'minioadmin:minioadmin'.
# MinIO recommends setting non-default values as a best practice, regardless of environment

MINIO_ROOT_USER=minioadmin
MINIO_ROOT_PASSWORD=minioadmin

# MINIO_VOLUMES sets the storage volume or path to use for the MinIO server.

MINIO_VOLUMES="/home/minio"

# MINIO_OPTS sets any additional commandline options to pass to the MinIO server.
# For example, `--console-address :9001` sets the MinIO Console listen port
MINIO_OPTS="--console-address :9001"

创建 minio 的用户和组

groupadd -r minio-user

useradd -M -r -g minio-user minio-user

chown minio-user:minio-user /home/minio

启动 MinIO 服务

  • 刷新 service 文件

    systemctl daemon-reload
    
  • 使 minio 服务在启动时启动

    systemctl enable minio.service
    
  • 启动 minio 服务

    systemctl start minio.service
    
    • 查看日志

      journalctl -f -u minio.service
      
  • 检查 minio服务的状态

    systemctl status minio.service
    

整合 SpringBoot

依赖

<dependency>
    <groupId>io.miniogroupId>
    <artifactId>minioartifactId>
    <version>8.5.17version>
dependency>

配置文件

minio:
  endpoint: 你安装minio的ip地址
  access-key: minioadmin
  secret-key: minioadmin
  bucket-name: 你的bucket名称

配置类

package com.management.demo.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.access-key}")
    private String accessKey;

    @Value("${minio.secret-key}")
    private String secretKey;

    @Bean
    public MinioClient minioClient() {
        return MinioClient.builder()
                .endpoint(endpoint)
                .credentials(accessKey, secretKey)
                .build();
    }
}

接口

package com.management.demo.service;

import io.minio.messages.Bucket;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.List;

public interface MinIOService {

    // 创建存储桶
    void createBucket(String bucketName) throws Exception;

    // 上传文件
    void uploadFile(String bucketName, String objectName, MultipartFile file) throws Exception;

    // 下载文件
    InputStream downloadFile(String bucketName, String objectName) throws Exception;

    // 删除文件
    void deleteFile(String bucketName, String objectName) throws Exception;

    // 获取文件URL
    String getObjectUrl(String bucketName, String objectName, int expiry) throws Exception;

    // 获取所有存储桶
    List<Bucket> listBuckets() throws Exception;

    // 检查存储桶是否存在
    boolean bucketExists(String bucketName) throws Exception;
}

实现

检查存储桶是否存在
@Override
public boolean bucketExists(String bucketName) throws Exception {
    return minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
}
创建存储桶
public void createBucket(String bucketName) throws Exception {
    if (!bucketExists(bucketName)) {
        minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
    }
}
上传文件
@Override
public void uploadFile(String bucketName, String objectName, MultipartFile file) throws Exception {
    InputStream inputStream = file.getInputStream();
    String contentType = file.getContentType();
    minioClient.putObject(PutObjectArgs.builder().bucket(bucketName).object(objectName)
            .stream(inputStream, inputStream.available(), -1).contentType(contentType).build());
}
下载文件
@Override
public InputStream downloadFile(String bucketName, String objectName) throws Exception {
    return minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(objectName).build());
}
删除文件
@Override
public void deleteFile(String bucketName, String objectName) throws Exception {
    minioClient.removeObject(RemoveObjectArgs.builder().bucket(bucketName).object(objectName).build());
}
获取文件url
@Override
public String getObjectUrl(String bucketName, String objectName, int expiry) throws Exception {
    return minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder()
            .method(Method.GET).bucket(bucketName).object(objectName).expiry(expiry).build());
}
获取所有存储桶
@Override
public List<Bucket> listBuckets() throws Exception {
    return minioClient.listBuckets();
}

使用

生成文件名的方法

public static String generatePicName(MultipartFile file) {
    String extension = FilenameUtils.getExtension(file.getOriginalFilename());
    return UUID.randomUUID().toString().replace("-", "").toUpperCase() + "." + extension;
}
上传文件
@PostMapping("/minio/upload")
public String uploadFile(@RequestParam("file") MultipartFile file) {
    try {
        String objectName = generatePicName(file);
        minIOService.uploadFile(bucketName, objectName, file);
        return objectName;
    } catch (Exception e) {
        return "上传文件失败";
    }
}
下载文件
@GetMapping("/download/{objectName}")
public void downloadFile(@PathVariable String objectName, HttpServletResponse response) {
    try (InputStream inputStream = minIOService.downloadFile(bucketName, objectName)) {
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(objectName, StandardCharsets.UTF_8));
        IOUtils.copy(inputStream, response.getOutputStream());
        response.flushBuffer();
    } catch (Exception e) {
        logger.error("下载文件失败");
    }
}
删除文件
@DeleteMapping("/delete/{objectName}")
public void deleteFile(@PathVariable String objectName) {
    try {
        minIOService.deleteFile(bucketName, objectName);
    } catch (Exception e) {
        logger.error("删除文件失败");
    }
}
获得文件地址
@GetMapping("/url/{objectName}")
public String getObjectUrl(@PathVariable String objectName) {
    try {
        return minIOService.getObjectUrl(objectName);
    } catch (Exception e) {
        logger.error(e.getMessage());
        return "获取文件地址失败";
    }
}

如果 bucket 权限是 public
获取图片地址使用 http://:// 即可直接访问

你可能感兴趣的:(学习笔记,java,spring,boot)