栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 系统运维 > 运维 > Linux

MinIo的模板封装

Linux 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

MinIo的模板封装

封装MinIO模块

使用SpringBoot的自动装配,把MinIO的Client进行封装,其他的微服务方便进行使用

docker :

docker run -id --name minio 
-v /opt/minio/data:/data 
-v /opt/minio/config:/root/.minio 
--restart=always -p 9000:9000 -p 9001:9001 
-e "MINIO_ACCESS_KEY=minio" -e "MINIO_SECRET_KEY=minio123" 
minio/minio:RELEASE.2022-04-16T04-26-02Z 
server /data --console-address ":9001"

图片步骤:

1 添加依赖

在heima-leadnews-common中添加依赖


    org.springframework.boot
    spring-boot-autoconfigure


    io.minio
    minio
    7.1.0


    org.springframework.boot
    spring-boot-starter


    org.springframework.boot
    spring-boot-configuration-processor
    true


    org.springframework.boot
    spring-boot-starter-actuator

2 配置类

在heima-leadnews-common中编写MinIOProperties,用来读取MinIO的配置信息

package com.heima.common.autoconfig.properties;


import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;

@Data
@ConfigurationProperties(prefix = "minio")  // 配置前缀
public class MinIOProperties {

    private String accessKey;
    private String secretKey;
    private String bucket;
    private String endpoint;
    private String readPath;
}
3 封装操作minIO类

在heima-leadnews-common中编写MinIOTemplate,用来操作MinIO的工具类

package com.heima.common.autoconfig.template;


import com.heima.common.autoconfig.properties.MinIOProperties;
import io.minio.GetObjectArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.RemoveObjectArgs;
import lombok.extern.slf4j.Slf4j;
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
public class MinIOTemplate {

    private MinioClient minioClient;
    private MinIOProperties minIOProperties;

    public MinIOTemplate(MinIOProperties minIOProperties) {
        this.minIOProperties = minIOProperties;
        this.minioClient = MinioClient
                .builder()
                .credentials(minIOProperties.getAccessKey(), minIOProperties.getSecretKey())
                .endpoint(minIOProperties.getEndpoint())
                .build();
    }


    private final static String separator = "/";

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

    
    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(minIOProperties.getBucket()).stream(inputStream, inputStream.available(), -1)
                    .build();
            minioClient.putObject(putObjectArgs);
            StringBuilder urlPath = new StringBuilder(minIOProperties.getReadPath());
            urlPath.append(separator + minIOProperties.getBucket());
            urlPath.append(separator);
            urlPath.append(filePath);
            return urlPath.toString();
        } catch (Exception ex) {
            log.error("minio put file error.", ex);
            throw new RuntimeException("上传文件失败");
        }
    }

    
    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(minIOProperties.getBucket()).stream(inputStream, inputStream.available(), -1)
                    .build();
            minioClient.putObject(putObjectArgs);
            StringBuilder urlPath = new StringBuilder(minIOProperties.getReadPath());
            urlPath.append(separator + minIOProperties.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("上传文件失败");
        }
    }

    
    public void delete(String pathUrl) {
        String key = pathUrl.replace(minIOProperties.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();
        }
    }


    
    public byte[] downLoadFile(String pathUrl) {
        String key = pathUrl.replace(minIOProperties.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(minIOProperties.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();
    }
}
4 对外加入自动配置

在heima-leadnews-common中编写LeadNewsAutoConfig,用来创建对象

package com.heima.common.autoconfig;

import com.heima.common.autoconfig.properties.MinIOProperties;
import com.heima.common.autoconfig.template.MinIOTemplate;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;


@EnableConfigurationProperties({MinIOProperties.class})
public class LeadNewsAutoConfig {

    @Bean
    //如果配置文件中有  minio.enable属性,且值为true,代表该方法会执行,否则不会执行
    @ConditionalOnProperty(prefix = "minio", value = "enable", havingValue = "true")
    public MinIOTemplate minIOTemplate(MinIOProperties minIOProperties) {
        return new MinIOTemplate( minIOProperties);
    }
}

在resources中修改META-INF/spring.factories

org.springframework.boot.autoconfigure.EnableAutoConfiguration=
  com.heima.common.exception.ExceptionCatch,
  com.heima.common.swagger.SwaggerConfiguration,
  com.heima.common.swagger.Swagger2Configuration
  com.heima.file.service.impl.MinIOFileStorageService
5 其他微服务使用

第一,在微服务中添加minio所需要的配置(例如heima-leadnews-article)

minio:
  accessKey: minio
  secretKey: minio123
  bucket: leadnews
  endpoint: http://192.168.200.128:9000
  readPath: http://192.168.200.128:9000
  enable: true #开启使用Minio 对应LeadNewsAutoConfig中的@ConditionalOnProperty注解属性

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

在heima-leadnews-article中进行测试

package com.heima.article.test;


import com.heima.article.ArticleApplication;
import com.heima.common.autoconfig.template.MinIOTemplate;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.FileInputStream;
import java.io.FileNotFoundException;

@SpringBootTest(classes = ArticleApplication.class)
public class MinioTest {

    @Autowired
    private MinIOTemplate minIOTemplate;

    @Test
    public void testUpdateImgFile() {
        try {
            FileInputStream fileInputStream = new FileInputStream("C:\Users\Tree-node2020\Downloads\d1cefe2e-f67c-4735-bc1c-0bedf14cd992.jpg");
            String filePath = minIOTemplate.uploadImgFile("", "tree1.jpg", fileInputStream);
            System.out.println(filePath);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/913492.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号