【Spring Cloud Alibaba】13.自建存储对象服务与集成(minio版)

简介

接下来对分布式项目实现存储对象服务器搭建与集成,本操作与前置步骤关系不大,大家可酌情查看前置步骤,详情请参照【Spring Cloud Alibaba】Spring Cloud Alibaba 搭建教程

什么是云存储服务(OSS)

OSS (Object Storage Service) 是一种云存储服务,用于存储和访问大量的非结构化数据,如图片、视频、文档等。它提供了高可靠性、高扩展性和低成本的存储解决方案,适用于各种云计算和大数据应用场景。

以下是一些常用的开源对象存储服务搭建技术:

  1. MinIO:专注于对象存储,具有高性能和易用性,适合用于存储大量的非结构化数据。
  2. Ceph:分布式存储系统,具有高可靠性和可扩展性,适合用于大规模存储和数据处理。
  3. Swift:OpenStack项目的一部分,提供对象存储服务,适合用于云存储和数据备份。
  4. HDFS:Apache Hadoop的分布式文件系统,适合用于大数据存储和处理。
  5. GlusterFS:分布式文件系统,具有高可用性和可扩展性,适合用于文件共享和存储。
  6. Ozone:Apache Hadoop的对象存储层,适合用于大规模对象存储和分析。

为什么选择MiniIO

对于云存储服务的集成大同小异,本文介绍的是MiniIO,至于为什么选择MiniIO,主要是因为搭建和集成方便,性能也不错,适合中小企业比较省心。

MiniIO相关地址

官网地址:https://min.io
官网文档:https://min.io/docs/minio/container/index.html

开源地址:

搭建(docker)

本问搭建方式选择的是docker,其他搭建方法参照官网搭建教程

安装Docker

已安装过的用户忽略此步骤,未安装的用户可以参照往期文章:
Centos安装docker
ubuntu安装docker
window安装docker

部署MinIO

创建文件持久化路径

mkdir -p ~/minio/data

创建并运行MinIO容器

docker run -d\
   --restart=always \
   -p 9876:9000 \
   -p 9878:9878 \
   --name minio \
   -v ~/minio/data:/data \
   -e "MINIO_ROOT_USER=moonce" \
   -e "MINIO_ROOT_PASSWORD=Mm123456" \
   quay.io/minio/minio server /data --console-address ":9878"

命令说明:

  • docker run:创建并启动容器;
  • --restart=always:跟随docker一起启动;
  • -p 9876:9000-p 9878:9878 :指定主机与容器端口映射,主机98769878分别对应容器90009878端口;
  • --name minio :指定容器名称为minio
  • -v ~/minio/data:/data:将主机路径 ~/minio/data与容器 /data映射,数据持久化存储;
  • -e "MINIO_ROOT_USER=moonce"-e "MINIO_ROOT_PASSWORD=Mm123456":设置默认用户名和密码;
  • quay.io/minio/minio:镜像地址,默认安装最新稳定版,需要指定版本加:版本
  • server /data:容器中文件存储位置
  • --console-address ":9878":指定UI控制台端口

创建完成后,打开服务器IP:9878
在这里插入图片描述
输入创建容器设置的账号密码,完成登录

创建存储桶

1.登录完成后,我们进入Buckets菜单,然后点击按钮Create Bucket
在这里插入图片描述
2.输入存储桶名称,无特殊要求的话,其他默认即可
在这里插入图片描述
配置说明

  • Versioning:允许在同一密钥下保留同一对象的多个版本。
  • Object Locking:可防止对象被删除。需要支持保留和合法保留。只能在创建存储桶时启用。
  • Quota :限制桶中的数据量。
  • Retention:施加规则以防止在一段时间内删除对象。必须启用版本控制才能设置存储桶保留策略。

配置存储桶

1.创建完成后我们在Buckets菜单中可以看到已经创建名为moonce的存储桶
在这里插入图片描述
2.点击这个存储桶,打开存储桶详细配置信息
在这里插入图片描述
功能项说明

  • EventsMinIO 存储桶通知允许管理员就某些对象或存储桶事件向支持的外部服务发送通知。 MinIO 支持与 Amazon S3 事件通知类似的存储桶和对象级 S3 事件。
  • ReplicationMinIO 支持源存储桶和目标存储桶之间的服务器端和客户端对象复制。
  • Lifecycle :MinIO 对象生命周期管理允许为基于时间或日期的对象自动转换或到期创建规则。对于对象转换,MinIO 自动将对象移动到配置的远程存储层。
  • Access :了解哪些政策和用户被授权接入这个桶。
  • Anonymous :设置匿名策略允许客户端无需认证即可访问Bucket或前缀内容并执行符合指定策略的操作。

设置存储桶可以直接在浏览器访问

选择Anonymous,点击Add Access Rule
在这里插入图片描述
创建新的匿名规则,让改存储桶下所有文件可以匿名只读
在这里插入图片描述
这样我们就可以直接在浏览器访问服务器IP:9876/moonce/存储桶中文件名.jpg来直接访问到文件。

集成到Spring Cloud Alibaba项目

创建子模块

参照【Spring Cloud Alibaba】3.创建服务提供者,创建服务提供者模块,命名为moonce-minio-provider

引入依赖包

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

如果允运行提示Unsupported OkHttp library found. Must use okhttp >= 4.12.0错误,则修改引用的okhttp版本

 <!-- minio oss -->
 <dependency>
       <groupId>io.minio</groupId>
       <artifactId>minio</artifactId>
       <version>8.5.10</version>
       <exclusions>
           <exclusion>
               <groupId>com.squareup.okhttp3</groupId>
               <artifactId>okhttp</artifactId>
           </exclusion>
       </exclusions>
   </dependency>
   <dependency>
       <groupId>com.squareup.okhttp3</groupId>
       <artifactId>okhttp</artifactId>
       <version>4.12.0</version>
   </dependency>

项目结构

在这里插入图片描述

配置文件

MinioConfig.java

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

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

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

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

参数配置(演示时没连nacos,正常应该将配置信息写到nacos中)
application.yml

server:
  port: 8081

management:
  endpoints:
    web:
      exposure:
        include: "*"
minio:
  #Minio服务所在地址
  endpoint: http://127.0.0.1:9876
  #存储桶名称
  bucketName: moonce
  #访问的key
  accessKey: moonce
  #访问的秘钥
  secretKey: Mm123465

工具类

MinioUtil.java


import com.moonce.provider.config.MinioConfig;
import io.minio.*;
import io.minio.http.Method;
import io.minio.messages.Bucket;
import io.minio.messages.Item;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
@Slf4j
public class MinioUtil {
    @Autowired
    private MinioConfig prop;

    @Resource
    private MinioClient minioClient;

    /**
     * 查看存储bucket是否存在
     * @return boolean
     */
    public Boolean bucketExists(String bucketName) {
        Boolean found;
        try {
            found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return found;
    }

    /**
     * 创建存储bucket
     * @return Boolean
     */
    public Boolean makeBucket(String bucketName) {
        try {
            minioClient.makeBucket(MakeBucketArgs.builder()
                    .bucket(bucketName)
                    .build());
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
    /**
     * 删除存储bucket
     * @return Boolean
     */
    public Boolean removeBucket(String bucketName) {
        try {
            minioClient.removeBucket(RemoveBucketArgs.builder()
                    .bucket(bucketName)
                    .build());
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
    /**
     * 获取全部bucket
     */
    public List<Bucket> getAllBuckets() {
        try {
            List<Bucket> buckets = minioClient.listBuckets();
            return buckets;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }



    /**
     * 文件上传
     *
     * @param file 文件
     * @return Boolean
     */
    public String upload(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        if (StringUtils.isBlank(originalFilename)){
            throw new RuntimeException();
        }
        String fileName = System.currentTimeMillis() + originalFilename.substring(originalFilename.lastIndexOf("."));
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM/dd");
        String formattedDate = sdf.format(new Date());

        String objectName = formattedDate + "/" + fileName;
        try {
            PutObjectArgs objectArgs = PutObjectArgs.builder().bucket(prop.getBucketName()).object(objectName)
                    .stream(file.getInputStream(), file.getSize(), -1).contentType(file.getContentType()).build();
            //文件名称相同会覆盖
            minioClient.putObject(objectArgs);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return objectName;
    }

    /**
     * 预览图片
     * @param fileName
     * @return
     */
    public String preview(String fileName){
        // 查看文件地址
        GetPresignedObjectUrlArgs build = new GetPresignedObjectUrlArgs().builder().bucket(prop.getBucketName()).object(fileName).method(Method.GET).build();
        try {
            String url = minioClient.getPresignedObjectUrl(build);
            return url;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 文件下载
     * @param fileName 文件名称
     * @param res response
     * @return Boolean
     */
    public void download(String fileName, HttpServletResponse res) {
        GetObjectArgs objectArgs = GetObjectArgs.builder().bucket(prop.getBucketName())
                .object(fileName).build();
        try {
            GetObjectResponse response = minioClient.getObject(objectArgs);
            byte[] buf = new byte[1024];
            int len;
            try (FastByteArrayOutputStream os = new FastByteArrayOutputStream()){
                while ((len=response.read(buf))!=-1){
                    os.write(buf,0,len);
                }
                os.flush();
                byte[] bytes = os.toByteArray();
                res.setCharacterEncoding("utf-8");
                // 设置强制下载不打开
                // res.setContentType("application/force-download");
                res.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
                try (ServletOutputStream stream = res.getOutputStream()){
                    stream.write(bytes);
                    stream.flush();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 查看文件对象
     * @return 存储bucket内文件对象信息
     */
    public List<Item> listObjects() {
        Iterable<Result<Item>> results = minioClient.listObjects(
                ListObjectsArgs.builder().bucket(prop.getBucketName()).build());
        List<Item> items = new ArrayList<>();
        try {
            for (Result<Item> result : results) {
                items.add(result.get());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return items;
    }

    /**
     * 删除
     * @param fileName
     * @return
     * @throws Exception
     */
    public boolean remove(String fileName){
        try {
            minioClient.removeObject( RemoveObjectArgs.builder().bucket(prop.getBucketName()).object(fileName).build());
        }catch (Exception e){
            return false;
        }
        return true;
    }

}

接口类

MinioController.java



import com.moonce.provider.config.MinioConfig;
import com.moonce.provider.util.MinioUtil;
import io.minio.messages.Bucket;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Slf4j
@RestController
@RequestMapping(value = "product/file")
public class MinioController {


    @Autowired
    private MinioUtil minioUtil;
    @Autowired
    private MinioConfig prop;

    /**
     * 查看存储bucket是否存在
     * @param bucketName
     * @return
     */
    @GetMapping("/bucketExists")
    public Boolean bucketExists(@RequestParam("bucketName") String bucketName) {
        return minioUtil.bucketExists(bucketName);
    }

    /**
     * 创建存储bucket
     * @param bucketName
     * @return
     */
    @GetMapping("/makeBucket")
    public Boolean makeBucket(String bucketName) {
        return minioUtil.makeBucket(bucketName);
    }

    /**
     * 删除存储bucket
     * @param bucketName
     * @return
     */
    @GetMapping("/removeBucket")
    public Boolean removeBucket(String bucketName) {
        return minioUtil.removeBucket(bucketName);
    }

    /**
     * 获取全部bucket
     * @return
     */
    @GetMapping("/getAllBuckets")
    public  List<Bucket> getAllBuckets() {
        List<Bucket> allBuckets = minioUtil.getAllBuckets();
        return allBuckets;
    }

    /**
     * 文件上传返回url
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public String upload(@RequestParam("file") MultipartFile file) {
        String objectName = minioUtil.upload(file);
        if (null != objectName) {
            return prop.getEndpoint() + "/" + prop.getBucketName() + "/" + objectName;
        }
        return "";
    }

    /**
     * 图片/视频预览
     * @param fileName
     * @return
     */
    @GetMapping("/preview")
    public String preview(@RequestParam("fileName") String fileName) {
        return minioUtil.preview(fileName);
    }

    /**
     * 文件下载
     * @param fileName
     * @param res
     * @return
     */
    @GetMapping("/download")
    public void download(@RequestParam("fileName") String fileName, HttpServletResponse res) {
        minioUtil.download(fileName,res);
    }

    /**
     * 删除文件
     * @param url
     * @return
     */
    @PostMapping("/delete")
    public String remove(String url) {
        String objName = url.substring(url.lastIndexOf(prop.getBucketName()+"/") + prop.getBucketName().length()+1);
        minioUtil.remove(objName);
        return objName;
    }

测试

在这里插入图片描述
访问返回地址,可正确打开图片!
在这里插入图片描述
在我们的minio控制台可以查询到该文件,上传路径中的/会自动分割成文件夹的形式!

相关推荐

  1. 开源项目_搭对象存储服务MinIO

    2024-06-07 22:46:06       39 阅读
  2. Docker搭MinIO私有对象存储

    2024-06-07 22:46:06       33 阅读
  3. Docker:使用MinIO对象存储平台

    2024-06-07 22:46:06       38 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-06-07 22:46:06       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-06-07 22:46:06       101 阅读
  3. 在Django里面运行非项目文件

    2024-06-07 22:46:06       82 阅读
  4. Python语言-面向对象

    2024-06-07 22:46:06       91 阅读

热门阅读

  1. PyCharm中快速搭建Python虚拟环境的指南

    2024-06-07 22:46:06       33 阅读
  2. 《effective c++》学习笔记

    2024-06-07 22:46:06       26 阅读
  3. npm yarn 更换国内源以及node历史版本下载地址

    2024-06-07 22:46:06       38 阅读
  4. leetcode 279.完全平方数

    2024-06-07 22:46:06       32 阅读
  5. 使用OpenCV进行简单图像分割的3个步骤

    2024-06-07 22:46:06       28 阅读
  6. ES 面试手册

    2024-06-07 22:46:06       29 阅读
  7. 2024河南高考作文ChatGPT

    2024-06-07 22:46:06       36 阅读