封装MinIO为starter

「工具类」https://www.aliyundrive.com/s/KY19YRm71jE
内有MinIO starter

3.5.1 创建模块heima-file-starter

导入依赖

  1. <dependencies>
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-autoconfigure</artifactId>
  5. </dependency>
  6. <dependency>
  7. <groupId>io.minio</groupId>
  8. <artifactId>minio</artifactId>
  9. <version>7.1.0</version>
  10. </dependency>
  11. <dependency>
  12. <groupId>org.springframework.boot</groupId>
  13. <artifactId>spring-boot-starter</artifactId>
  14. </dependency>
  15. <dependency>
  16. <groupId>org.springframework.boot</groupId>
  17. <artifactId>spring-boot-configuration-processor</artifactId>
  18. <optional>true</optional>
  19. </dependency>
  20. <dependency>
  21. <groupId>org.springframework.boot</groupId>
  22. <artifactId>spring-boot-starter-actuator</artifactId>
  23. </dependency>
  24. </dependencies>

3.5.2 配置类

MinIOConfigProperties

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

MinIOConfig

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

3.5.3 封装操作minIO类

FileStorageService

  1. package com.heima.file.service;
  2. import java.io.InputStream;
  3. /**
  4. * @author itheima
  5. */
  6. public interface FileStorageService {
  7. /**
  8. * 上传图片文件
  9. * @param prefix 文件前缀
  10. * @param filename 文件名
  11. * @param inputStream 文件流
  12. * @return 文件全路径
  13. */
  14. public String uploadImgFile(String prefix, String filename,InputStream inputStream);
  15. /**
  16. * 上传html文件
  17. * @param prefix 文件前缀
  18. * @param filename 文件名
  19. * @param inputStream 文件流
  20. * @return 文件全路径
  21. */
  22. public String uploadHtmlFile(String prefix, String filename,InputStream inputStream);
  23. /**
  24. * 删除文件
  25. * @param pathUrl 文件全路径
  26. */
  27. public void delete(String pathUrl);
  28. /**
  29. * 下载文件
  30. * @param pathUrl 文件全路径
  31. * @return
  32. *
  33. */
  34. public byte[] downLoadFile(String pathUrl);
  35. }

MinIOFileStorageService

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

3.5.4 对外加入自动配置

在resources中新建META-INF/spring.factories

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

3.5.5 其他微服务使用

第一,导入heima-file-starter的依赖

第二,在微服务中添加minio所需要的配置

  1. minio:
  2. accessKey: minio
  3. secretKey: minio123
  4. bucket: leadnews
  5. endpoint: http://192.168.200.130:9000
  6. readPath: http://192.168.200.130:9000

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

  1. package com.heima.minio.test;
  2. import com.heima.file.service.FileStorageService;
  3. import com.heima.minio.MinioApplication;
  4. import org.junit.Test;
  5. import org.junit.runner.RunWith;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.boot.test.context.SpringBootTest;
  8. import org.springframework.test.context.junit4.SpringRunner;
  9. import java.io.FileInputStream;
  10. import java.io.FileNotFoundException;
  11. @SpringBootTest(classes = MinioApplication.class)
  12. @RunWith(SpringRunner.class)
  13. public class MinioTest {
  14. @Autowired
  15. private FileStorageService fileStorageService;
  16. @Test
  17. public void testUpdateImgFile() {
  18. try {
  19. FileInputStream fileInputStream = new FileInputStream("E:\\tmp\\ak47.jpg");
  20. String filePath = fileStorageService.uploadImgFile("", "ak47.jpg", fileInputStream);
  21. System.out.println(filePath);
  22. } catch (FileNotFoundException e) {
  23. e.printStackTrace();
  24. }
  25. }
  26. }