• SpringBoot+MinIO(三)


    一、MinIO特点

    • 数据保护

      Minio使用Minio Erasure Code(纠删码)来防止硬件故障。即便损坏一半以上的driver,但是仍然可以从中恢复。

    • 高性能

      作为高性能对象存储,在标准硬件条件下它能达到55GB/s的读、35GB/s的写速率

    • 可扩容

      不同MinIO集群可以组成联邦,并形成一个全局的命名空间,并跨越多个数据中心

    • SDK支持

      基于Minio轻量的特点,它得到类似Java、Python或Go等语言的sdk支持

    • 有操作页面

      面向用户友好的简单操作界面,非常方便的管理Bucket及里面的文件资源

    • 功能简单

      这一设计原则让MinIO不容易出错、更快启动

    • 丰富的API

      支持文件资源的分享连接及分享链接的过期策略、存储桶操作、文件列表访问及文件上传下载的基本功能等。

    • 文件变化主动通知

      存储桶(Bucket)如果发生改变,比如上传对象和删除对象,可以使用存储桶事件通知机制进行监控,并通过以下方式发布出去:AMQP、MQTT、Elasticsearch、Redis、NATS、MySQL、Kafka、Webhooks等。

    二、在docker中的使用

    2.1

    1.将镜像下载到docker
    2.在用docker进行环境的部署

    docker run -p 9000:9000 --name minio -d --restart=always -e "MINIO_ACCESS_KEY=minio" -e "MINIO_SECRET_KEY=minio123" -v /home/data:/data -v /home/config:/root/.minio minio/minio server /data
    
    • 1

    3.如何访问:
    假设我们的服务器地址为http://192.168.200.130:9000,我们在地址栏输入:http://http://192.168.200.130:9000/ 即可进入登录界面。
    Access Key为minio
    Secret_key 为minio123 进入系统后可以看到主界面

    2.2 使用

    1.在pom中加入依赖

      <dependencies>
    
            <dependency>
                <groupId>io.minio</groupId>
                <artifactId>minio</artifactId>
                <version>7.1.0</version>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
            </dependency>
        </dependencies>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    2.添加引导类

    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    
    @SpringBootApplication
    public class MinIOApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(MinIOApplication.class,args);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    创建测试类,上传html文件

    import io.minio.MinioClient;
    import io.minio.PutObjectArgs;
    
    import java.io.FileInputStream;
    
    public class MinIOTest {
    
    
        public static void main(String[] args) {
    
            FileInputStream fileInputStream = null;
            try {
    
                fileInputStream =  new FileInputStream("D:\\list.html");;
    
                //1.创建minio链接客户端
                MinioClient minioClient = MinioClient.builder().credentials("minio", "minio123").endpoint("http://192.168.200.130:9000").build();
                //2.上传
                PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                        .object("list.html")//文件名
                        .contentType("text/html")//文件类型
                        .bucket("leadnews")//桶名词  与minio创建的名词一致
                        .stream(fileInputStream, fileInputStream.available(), -1) //文件流
                        .build();
                minioClient.putObject(putObjectArgs);
    
                System.out.println("http://192.168.200.130:9000/leadnews/ak47.jpg");
    
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34

    三、封装MinIO为starter

    3.1 创建模块heima-file-starter,导入依赖

    <dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-autoconfigureartifactId>
        dependency>
        <dependency>
            <groupId>io.miniogroupId>
            <artifactId>minioartifactId>
            <version>7.1.0version>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starterartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-configuration-processorartifactId>
            <optional>trueoptional>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-actuatorartifactId>
        dependency>
    dependencies>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    3.2 配置类

    MinIOConfigProperties,用来接收nacos中的配置信息:

    import lombok.Data;
    import org.springframework.boot.context.properties.ConfigurationProperties;
    
    import java.io.Serializable;
    
    @Data
    @ConfigurationProperties(prefix = "minio")  // 文件上传 配置前缀file.oss
    public class MinIOConfigProperties implements Serializable {
    
        private String accessKey;
        private String secretKey;
        private String bucket;
        private String endpoint;
        private String readPath;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    MinIOConfig:

    import com.heima.file.service.FileStorageService;
    import io.minio.MinioClient;
    import lombok.Data;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
    import org.springframework.boot.context.properties.EnableConfigurationProperties;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    
    
    @Data
    @Configuration
    @EnableConfigurationProperties({MinIOConfigProperties.class})
    //当引入FileStorageService接口时
    @ConditionalOnClass(FileStorageService.class)
    public class MinIOConfig {
    
       @Autowired
       private MinIOConfigProperties minIOConfigProperties;
    
        @Bean
        public MinioClient buildMinioClient(){
            return MinioClient
                    .builder()
                    .credentials(minIOConfigProperties.getAccessKey(), minIOConfigProperties.getSecretKey())
                    .endpoint(minIOConfigProperties.getEndpoint())
                    .build();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29

    3.3封装操作minIO类

    FileStorageService

    import io.minio.PutObjectArgs;
    import io.minio.RemoveObjectArgs;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.List;
    
    /**
     * @author itheima
     */
    public interface FileStorageService {
    
    
        /**
         *  上传图片文件
         * @param prefix  文件前缀
         * @param filename  文件名
         * @param inputStream 文件流
         * @return  文件全路径
         */
        public String uploadImgFile(String prefix, String filename,InputStream inputStream);
    
        /**
         *  上传html文件
         * @param prefix  文件前缀
         * @param filename   文件名
         * @param inputStream  文件流
         * @return  文件全路径
         */
        public String uploadHtmlFile(String prefix, String filename,InputStream inputStream);
    
        /**
         * 删除文件
         * @param pathUrl  文件全路径
         */
        public void delete(String pathUrl);
    
        /**
         * 下载文件
         * @param pathUrl  文件全路径
         * @return  文件流
         *
         */
        public InputStream downFile(String pathUrl);
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46

    MinIOFileStorageService:

    import com.heima.file.config.MinIOConfig;
    import com.heima.file.config.MinIOConfigProperties;
    import com.heima.file.service.FileStorageService;
    import io.minio.GetObjectArgs;
    import io.minio.MinioClient;
    import io.minio.PutObjectArgs;
    import io.minio.RemoveObjectArgs;
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.context.properties.EnableConfigurationProperties;
    import org.springframework.context.annotation.Import;
    import org.springframework.util.StringUtils;
    
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    @Slf4j
    @EnableConfigurationProperties(MinIOConfigProperties.class)
    @Import(MinIOConfig.class)
    public class MinIOFileStorageService implements FileStorageService {
    
        @Autowired
        private MinioClient minioClient;
    
        @Autowired
        private MinIOConfigProperties minIOConfigProperties;
    
        private final static String separator = "/";
    
        /**
         * @param dirPath
         * @param filename  yyyy/mm/dd/file.jpg
         * @return
         */
        public String builderFilePath(String dirPath,String filename) {
            StringBuilder stringBuilder = new StringBuilder(50);
            if(!StringUtils.isEmpty(dirPath)){
                stringBuilder.append(dirPath).append(separator);
            }
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
            String todayStr = sdf.format(new Date());
            stringBuilder.append(todayStr).append(separator);
            stringBuilder.append(filename);
            return stringBuilder.toString();
        }
    
        /**
         *  上传图片文件
         * @param prefix  文件前缀
         * @param filename  文件名
         * @param inputStream 文件流
         * @return  文件全路径
         */
        @Override
        public String uploadImgFile(String prefix, String filename,InputStream inputStream) {
            String filePath = builderFilePath(prefix, filename);
            try {
                PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                        .object(filePath)
                        .contentType("image/jpg")
                        .bucket(minIOConfigProperties.getBucket()).stream(inputStream,inputStream.available(),-1)
                        .build();
                minioClient.putObject(putObjectArgs);
                StringBuilder urlPath = new StringBuilder(minIOConfigProperties.getReadPath());
                urlPath.append(separator+minIOConfigProperties.getBucket());
                urlPath.append(separator);
                urlPath.append(filePath);
                return urlPath.toString();
            }catch (Exception ex){
                log.error("minio put file error.",ex);
                throw new RuntimeException("上传文件失败");
            }
        }
    
        /**
         *  上传html文件
         * @param prefix  文件前缀
         * @param filename   文件名
         * @param inputStream  文件流
         * @return  文件全路径
         */
        @Override
        public String uploadHtmlFile(String prefix, String filename,InputStream inputStream) {
            String filePath = builderFilePath(prefix, filename);
            try {
                PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                        .object(filePath)
                        .contentType("text/html")
                        .bucket(minIOConfigProperties.getBucket()).stream(inputStream,inputStream.available(),-1)
                        .build();
                minioClient.putObject(putObjectArgs);
                StringBuilder urlPath = new StringBuilder(minIOConfigProperties.getReadPath());
                urlPath.append(separator+minIOConfigProperties.getBucket());
                urlPath.append(separator);
                urlPath.append(filePath);
                return urlPath.toString();
            }catch (Exception ex){
                log.error("minio put file error.",ex);
                ex.printStackTrace();
                throw new RuntimeException("上传文件失败");
            }
        }
    
        /**
         * 删除文件
         * @param pathUrl  文件全路径
         */
        @Override
        public void delete(String pathUrl) {
            String key = pathUrl.replace(minIOConfigProperties.getEndpoint()+"/","");
            int index = key.indexOf(separator);
            String bucket = key.substring(0,index);
            String filePath = key.substring(index+1);
            // 删除Objects
            RemoveObjectArgs removeObjectArgs = RemoveObjectArgs.builder().bucket(bucket).object(filePath).build();
            try {
                minioClient.removeObject(removeObjectArgs);
            } catch (Exception e) {
                log.error("minio remove file error.  pathUrl:{}",pathUrl);
                e.printStackTrace();
            }
        }
    
    
        /**
         * 下载文件
         * @param pathUrl  文件全路径
         * @return  文件流
         *
         */
        @Override
        public byte[] downLoadFile(String pathUrl)  {
            String key = pathUrl.replace(minIOConfigProperties.getEndpoint()+"/","");
            int index = key.indexOf(separator);
            String bucket = key.substring(0,index);
            String filePath = key.substring(index+1);
            InputStream inputStream = null;
            try {
                inputStream = minioClient.getObject(GetObjectArgs.builder().bucket(minIOConfigProperties.getBucket()).object(filePath).build());
            } catch (Exception e) {
                log.error("minio down file error.  pathUrl:{}",pathUrl);
                e.printStackTrace();
            }
    
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] buff = new byte[100];
            int rc = 0;
            while (true) {
                try {
                    if (!((rc = inputStream.read(buff, 0, 100)) > 0)) break;
                } catch (IOException e) {
                    e.printStackTrace();
                }
                byteArrayOutputStream.write(buff, 0, rc);
            }
            return byteArrayOutputStream.toByteArray();
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162

    3.4 对外加入自动配置

    在resources中新建META-INF/spring.factories,让spring启动时会自动扫描类,并生成bean实例

    org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
      com.heima.file.service.impl.MinIOFileStorageService
    
    • 1
    • 2

    3.5其他微服务的使用

    第一,导入heima-file-starter的依赖
    第二,在微服务中添加minio所需要的配置

    minio:
      accessKey: minio
      secretKey: minioxxx
      bucket: leadnews
      endpoint: http://192.168.xxx.130:9000
      readPath: http://192.168.xxx.130:9000
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    第三,在对应使用的业务类中注入FileStorageService,样例如下:

    import com.heima.file.service.FileStorageService;
    import com.heima.minio.MinioApplication;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.test.context.junit4.SpringRunner;
    
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    
    @SpringBootTest(classes = MinioApplication.class)
    @RunWith(SpringRunner.class)
    public class MinioTest {
    
        @Autowired
        private FileStorageService fileStorageService;
    
        @Test
        public void testUpdateImgFile() {
            try {
                FileInputStream fileInputStream = new FileInputStream("E:\\tmp\\ak47.jpg");
                String filePath = fileStorageService.uploadImgFile("", "ak47.jpg", fileInputStream);
                System.out.println(filePath);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
  • 相关阅读:
    【微服务~原始真解】Spring Cloud —— 实现负载均衡
    Android-NDK-clang 编译 FFmpeg
    腾讯联手警方重拳出击 《绝地求生》外挂首案告破
    在CentOS编译Git源码
    c++多态
    IntelliJ IDEA的快速配置详细使用
    不得不说,在很多业务中,这种模式用得真的很香
    java计算机毕业设计考勤系统设计MyBatis+系统+LW文档+源码+调试部署
    04-Redis 持久化AOF你真的了解吗?
    电力系统IEEE14节点系统同步模型(Simulink)
  • 原文地址:https://blog.csdn.net/m0_45101736/article/details/126912842