当前位置:   article > 正文

Minio工具类 - Java_minioutils

minioutils

pom.xml中引依赖

  1. <dependency>
  2. <groupId>io.minio</groupId>
  3. <artifactId>minio</artifactId>
  4. <version>7.1.0</version>
  5. </dependency>

配置

  1. minio:
  2. endpoint: http://127.0.0.1:9000 #MinIO服务所在地址
  3. bucketName: test #存储桶名称
  4. accessKey: admin #访问的key
  5. secretKey: admin123 #访问的秘钥

项目启动,创建bean:MinioConfig.java

  1. import com.mgmiot.dlp.file.utils.MinioUtils;
  2. import lombok.extern.slf4j.Slf4j;
  3. import org.springframework.beans.factory.annotation.Value;
  4. import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
  5. import org.springframework.context.annotation.Bean;
  6. import org.springframework.context.annotation.Configuration;
  7. import org.springframework.integration.annotation.IntegrationComponentScan;
  8. /**
  9. * @Author: zrs
  10. * @Date: 2020/12/01/17:05
  11. * @Description: 创建Bean
  12. */
  13. @Configuration
  14. @IntegrationComponentScan
  15. @Slf4j
  16. public class MinioConfig {
  17. @Value("${minio.endpoint}")
  18. private String endpoint;
  19. @Value("${minio.bucketName}")
  20. private String bucketName;
  21. @Value("${minio.accessKey}")
  22. private String accessKey;
  23. @Value("${minio.secretKey}")
  24. private String secretKey;
  25. @Bean
  26. public MinioUtils creatMinioClient() {
  27. return new MinioUtils(endpoint, bucketName, accessKey, secretKey);
  28. }
  29. }

Minio工具类:MinioUtils.java

  1. import com.alibaba.fastjson.JSONObject;
  2. import io.minio.BucketExistsArgs;
  3. import io.minio.CopyObjectArgs;
  4. import io.minio.CopySource;
  5. import io.minio.GetBucketPolicyArgs;
  6. import io.minio.GetObjectArgs;
  7. import io.minio.ListObjectsArgs;
  8. import io.minio.MakeBucketArgs;
  9. import io.minio.MinioClient;
  10. import io.minio.ObjectStat;
  11. import io.minio.ObjectWriteResponse;
  12. import io.minio.PostPolicy;
  13. import io.minio.PutObjectArgs;
  14. import io.minio.RemoveBucketArgs;
  15. import io.minio.RemoveObjectArgs;
  16. import io.minio.Result;
  17. import io.minio.StatObjectArgs;
  18. import io.minio.UploadObjectArgs;
  19. import io.minio.errors.BucketPolicyTooLargeException;
  20. import io.minio.errors.ErrorResponseException;
  21. import io.minio.errors.InsufficientDataException;
  22. import io.minio.errors.InternalException;
  23. import io.minio.errors.InvalidBucketNameException;
  24. import io.minio.errors.InvalidExpiresRangeException;
  25. import io.minio.errors.InvalidResponseException;
  26. import io.minio.errors.RegionConflictException;
  27. import io.minio.errors.ServerException;
  28. import io.minio.errors.XmlParserException;
  29. import io.minio.messages.Bucket;
  30. import io.minio.messages.DeleteObject;
  31. import io.minio.messages.Item;
  32. import java.io.ByteArrayInputStream;
  33. import java.io.IOException;
  34. import java.io.InputStream;
  35. import java.io.UnsupportedEncodingException;
  36. import java.net.URLDecoder;
  37. import java.security.InvalidKeyException;
  38. import java.security.NoSuchAlgorithmException;
  39. import java.time.ZonedDateTime;
  40. import java.util.ArrayList;
  41. import java.util.LinkedList;
  42. import java.util.List;
  43. import java.util.Map;
  44. import java.util.Optional;
  45. import lombok.extern.slf4j.Slf4j;
  46. import org.springframework.web.multipart.MultipartFile;
  47. /**
  48. * @Author: zrs
  49. * @Date: 2020/12/01/10:02
  50. * @Description: Minio工具类
  51. */
  52. @Slf4j
  53. public class MinioUtils {
  54. private static MinioClient minioClient;
  55. private static String endpoint;
  56. private static String bucketName;
  57. private static String accessKey;
  58. private static String secretKey;
  59. private static final String SEPARATOR = "/";
  60. private MinioUtils() {
  61. }
  62. public MinioUtils(String endpoint, String bucketName, String accessKey, String secretKey) {
  63. MinioUtils.endpoint = endpoint;
  64. MinioUtils.bucketName = bucketName;
  65. MinioUtils.accessKey = accessKey;
  66. MinioUtils.secretKey = secretKey;
  67. createMinioClient();
  68. }
  69. /**
  70. * 创建minioClient
  71. */
  72. public void createMinioClient() {
  73. try {
  74. if (null == minioClient) {
  75. log.info("minioClient create start");
  76. minioClient = MinioClient.builder().endpoint(endpoint).credentials(accessKey, secretKey)
  77. .build();
  78. createBucket();
  79. log.info("minioClient create end");
  80. }
  81. } catch (Exception e) {
  82. log.error("连接MinIO服务器异常:{}", e);
  83. }
  84. }
  85. /**
  86. * 获取上传文件的基础路径
  87. *
  88. * @return url
  89. */
  90. public static String getBasisUrl() {
  91. return endpoint + SEPARATOR + bucketName + SEPARATOR;
  92. }
  93. 操作存储桶
  94. /**
  95. * 初始化Bucket
  96. *
  97. * @throws Exception 异常
  98. */
  99. private static void createBucket()
  100. throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException, RegionConflictException {
  101. if (!minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build())) {
  102. minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
  103. }
  104. }
  105. /**
  106. * 验证bucketName是否存在
  107. *
  108. * @return boolean true:存在
  109. */
  110. public static boolean bucketExists()
  111. throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {
  112. return minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
  113. }
  114. /**
  115. * 创建bucket
  116. *
  117. * @param bucketName bucket名称
  118. */
  119. public static void createBucket(String bucketName)
  120. throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException, RegionConflictException {
  121. if (!minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build())) {
  122. minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
  123. }
  124. }
  125. /**
  126. * 获取存储桶策略
  127. *
  128. * @param bucketName 存储桶名称
  129. * @return json
  130. */
  131. private JSONObject getBucketPolicy(String bucketName)
  132. throws IOException, InvalidKeyException, InvalidResponseException, BucketPolicyTooLargeException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, InsufficientDataException, ErrorResponseException {
  133. String bucketPolicy = minioClient
  134. .getBucketPolicy(GetBucketPolicyArgs.builder().bucket(bucketName).build());
  135. return JSONObject.parseObject(bucketPolicy);
  136. }
  137. /**
  138. * 获取全部bucket
  139. * <p>
  140. * https://docs.minio.io/cn/java-client-api-reference.html#listBuckets
  141. */
  142. public static List<Bucket> getAllBuckets()
  143. throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {
  144. return minioClient.listBuckets();
  145. }
  146. /**
  147. * 根据bucketName获取信息
  148. *
  149. * @param bucketName bucket名称
  150. */
  151. public static Optional<Bucket> getBucket(String bucketName)
  152. throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {
  153. return minioClient.listBuckets().stream().filter(b -> b.name().equals(bucketName)).findFirst();
  154. }
  155. /**
  156. * 根据bucketName删除信息
  157. *
  158. * @param bucketName bucket名称
  159. */
  160. public static void removeBucket(String bucketName)
  161. throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {
  162. minioClient.removeBucket(RemoveBucketArgs.builder().bucket(bucketName).build());
  163. }
  164. 操作文件对象
  165. /**
  166. * 判断文件是否存在
  167. *
  168. * @param bucketName 存储桶
  169. * @param objectName 对象
  170. * @return true:存在
  171. */
  172. public static boolean doesObjectExist(String bucketName, String objectName) {
  173. boolean exist = true;
  174. try {
  175. minioClient
  176. .statObject(StatObjectArgs.builder().bucket(bucketName).object(objectName).build());
  177. } catch (Exception e) {
  178. exist = false;
  179. }
  180. return exist;
  181. }
  182. /**
  183. * 判断文件夹是否存在
  184. *
  185. * @param bucketName 存储桶
  186. * @param objectName 文件夹名称(去掉/)
  187. * @return true:存在
  188. */
  189. public static boolean doesFolderExist(String bucketName, String objectName) {
  190. boolean exist = false;
  191. try {
  192. Iterable<Result<Item>> results = minioClient.listObjects(
  193. ListObjectsArgs.builder().bucket(bucketName).prefix(objectName).recursive(false).build());
  194. for (Result<Item> result : results) {
  195. Item item = result.get();
  196. if (item.isDir() && objectName.equals(item.objectName())) {
  197. exist = true;
  198. }
  199. }
  200. } catch (Exception e) {
  201. exist = false;
  202. }
  203. return exist;
  204. }
  205. /**
  206. * 根据文件前置查询文件
  207. *
  208. * @param bucketName bucket名称
  209. * @param prefix 前缀
  210. * @param recursive 是否递归查询
  211. * @return MinioItem 列表
  212. */
  213. public static List<Item> getAllObjectsByPrefix(String bucketName, String prefix,
  214. boolean recursive)
  215. throws ErrorResponseException, InsufficientDataException, InternalException, InvalidBucketNameException, InvalidKeyException, InvalidResponseException,
  216. IOException, NoSuchAlgorithmException, ServerException, XmlParserException {
  217. List<Item> list = new ArrayList<>();
  218. Iterable<Result<Item>> objectsIterator = minioClient.listObjects(
  219. ListObjectsArgs.builder().bucket(bucketName).prefix(prefix).recursive(recursive).build());
  220. if (objectsIterator != null) {
  221. for (Result<Item> o : objectsIterator) {
  222. Item item = o.get();
  223. list.add(item);
  224. }
  225. }
  226. return list;
  227. }
  228. /**
  229. * 获取文件流
  230. *
  231. * @param bucketName bucket名称
  232. * @param objectName 文件名称
  233. * @return 二进制流
  234. */
  235. public static InputStream getObject(String bucketName, String objectName)
  236. throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {
  237. return minioClient
  238. .getObject(GetObjectArgs.builder().bucket(bucketName).object(objectName).build());
  239. }
  240. /**
  241. * 断点下载
  242. *
  243. * @param bucketName bucket名称
  244. * @param objectName 文件名称
  245. * @param offset 起始字节的位置
  246. * @param length 要读取的长度
  247. * @return
  248. */
  249. public InputStream getObject(String bucketName, String objectName, long offset, long length)
  250. throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {
  251. return minioClient.getObject(
  252. GetObjectArgs.builder().bucket(bucketName).object(objectName).offset(offset).length(length)
  253. .build());
  254. }
  255. /**
  256. * 获取路径下文件列表
  257. *
  258. * @param bucketName bucket名称
  259. * @param prefix 文件名称
  260. * @param recursive 是否递归查找,如果是false,就模拟文件夹结构查找
  261. * @return 二进制流
  262. */
  263. public static Iterable<Result<Item>> listObjects(String bucketName, String prefix,
  264. boolean recursive) {
  265. return minioClient.listObjects(
  266. ListObjectsArgs.builder().bucket(bucketName).prefix(prefix).recursive(recursive).build());
  267. }
  268. /**
  269. * 通过MultipartFile,上传文件
  270. *
  271. * @param bucketName 存储桶
  272. * @param file 文件
  273. * @param objectName 对象名
  274. */
  275. public static ObjectWriteResponse putObject(String bucketName, MultipartFile file,
  276. String objectName, String contentType)
  277. throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {
  278. InputStream inputStream = file.getInputStream();
  279. return minioClient.putObject(
  280. PutObjectArgs.builder().bucket(bucketName).object(objectName).contentType(contentType)
  281. .stream(
  282. inputStream, inputStream.available(), -1)
  283. .build());
  284. }
  285. /**
  286. * 上传本地文件
  287. *
  288. * @param bucketName 存储桶
  289. * @param objectName 对象名称
  290. * @param fileName 本地文件路径
  291. */
  292. public static ObjectWriteResponse putObject(String bucketName, String objectName,
  293. String fileName)
  294. throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {
  295. return minioClient.uploadObject(
  296. UploadObjectArgs.builder()
  297. .bucket(bucketName).object(objectName).filename(fileName).build());
  298. }
  299. /**
  300. * 通过流上传文件
  301. *
  302. * @param bucketName 存储桶
  303. * @param objectName 文件对象
  304. * @param inputStream 文件流
  305. */
  306. public static ObjectWriteResponse putObject(String bucketName, String objectName,
  307. InputStream inputStream)
  308. throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {
  309. return minioClient.putObject(
  310. PutObjectArgs.builder().bucket(bucketName).object(objectName).stream(
  311. inputStream, inputStream.available(), -1)
  312. .build());
  313. }
  314. /**
  315. * 创建文件夹或目录
  316. *
  317. * @param bucketName 存储桶
  318. * @param objectName 目录路径
  319. */
  320. public static ObjectWriteResponse putDirObject(String bucketName, String objectName)
  321. throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {
  322. return minioClient.putObject(
  323. PutObjectArgs.builder().bucket(bucketName).object(objectName).stream(
  324. new ByteArrayInputStream(new byte[]{}), 0, -1)
  325. .build());
  326. }
  327. /**
  328. * 获取文件信息, 如果抛出异常则说明文件不存在
  329. *
  330. * @param bucketName bucket名称
  331. * @param objectName 文件名称
  332. */
  333. public static ObjectStat statObject(String bucketName, String objectName)
  334. throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {
  335. return minioClient
  336. .statObject(StatObjectArgs.builder().bucket(bucketName).object(objectName).build());
  337. }
  338. /**
  339. * 拷贝文件
  340. *
  341. * @param bucketName bucket名称
  342. * @param objectName 文件名称
  343. * @param srcBucketName 目标bucket名称
  344. * @param srcObjectName 目标文件名称
  345. */
  346. public static ObjectWriteResponse copyObject(String bucketName, String objectName,
  347. String srcBucketName, String srcObjectName)
  348. throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {
  349. return minioClient.copyObject(
  350. CopyObjectArgs.builder()
  351. .source(CopySource.builder().bucket(bucketName).object(objectName).build())
  352. .bucket(srcBucketName)
  353. .object(srcObjectName)
  354. .build());
  355. }
  356. /**
  357. * 删除文件
  358. *
  359. * @param bucketName bucket名称
  360. * @param objectName 文件名称
  361. */
  362. public static void removeObject(String bucketName, String objectName)
  363. throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {
  364. minioClient
  365. .removeObject(RemoveObjectArgs.builder().bucket(bucketName).object(objectName).build());
  366. }
  367. /**
  368. * 批量删除文件
  369. *
  370. * @param bucketName bucket
  371. * @param keys 需要删除的文件列表
  372. * @return
  373. */
  374. /*public static Iterable<Result<DeleteError>> removeObjects(String bucketName, List<String> keys) {
  375. List<DeleteObject> objects = new LinkedList<>();
  376. keys.forEach(s -> {
  377. objects.add(new DeleteObject(s));
  378. });
  379. return minioClient.removeObjects(
  380. RemoveObjectsArgs.builder().bucket(bucketName).objects(objects).build());
  381. }*/
  382. public static void removeObjects(String bucketName, List<String> keys) {
  383. List<DeleteObject> objects = new LinkedList<>();
  384. keys.forEach(s -> {
  385. objects.add(new DeleteObject(s));
  386. try {
  387. removeObject(bucketName, s);
  388. } catch (Exception e) {
  389. log.error("批量删除失败!error:{}",e);
  390. }
  391. });
  392. }
  393. 操作Presigned
  394. /**
  395. * 获取文件外链
  396. *
  397. * @param bucketName bucket名称
  398. * @param objectName 文件名称
  399. * @param expires 过期时间 <=7 秒级
  400. * @return url
  401. */
  402. public static String getPresignedObjectUrl(String bucketName, String objectName,
  403. Integer expires)
  404. throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, InvalidExpiresRangeException, ServerException, InternalException, NoSuchAlgorithmException, XmlParserException, InvalidBucketNameException, ErrorResponseException {
  405. return minioClient.presignedGetObject(bucketName, objectName, expires);
  406. }
  407. /**
  408. * 给presigned URL设置策略
  409. *
  410. * @param bucketName 存储桶
  411. * @param objectName 对象名
  412. * @param expires 过期策略
  413. * @return map
  414. */
  415. public static Map<String, String> presignedGetObject(String bucketName, String objectName,
  416. Integer expires)
  417. throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, InvalidExpiresRangeException, ServerException, InternalException, NoSuchAlgorithmException, XmlParserException, InvalidBucketNameException, ErrorResponseException {
  418. PostPolicy policy = new PostPolicy(bucketName, objectName,
  419. ZonedDateTime.now().plusDays(7));
  420. policy.setContentType("image/png");
  421. return minioClient.presignedPostPolicy(policy);
  422. }
  423. /**
  424. * 将URLDecoder编码转成UTF8
  425. *
  426. * @param str
  427. * @return
  428. * @throws UnsupportedEncodingException
  429. */
  430. public static String getUtf8ByURLDecoder(String str) throws UnsupportedEncodingException {
  431. String url = str.replaceAll("%(?![0-9a-fA-F]{2})", "%25");
  432. return URLDecoder.decode(url, "UTF-8");
  433. }
  434. }

如果想使用AWS-S3的方式实现通用存储操作,可以看我这篇文章:https://blog.csdn.net/weixin_42170236/article/details/130870166

手写不易,有用请点赞!

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Gausst松鼠会/article/detail/110938
推荐阅读
相关标签
  

闽ICP备14008679号