• SpringBoot使用Maven整合minio实现静态资源和对象的存储;解决与okhttp依赖冲突问题


    1.minio部署

    推荐使用DockerCompose部署

    可参考下面的地址:
    Minio官网(中文):http://www.minio.org.cn/
    DockerHub地址:https://hub.docker.com/r/minio/minio
    DockerCompose部署minio:Docker使用docker compose单机部署对象存储系统minio (2022新版本)

    2.添加maven依赖

    在这里插入图片描述

    依赖:

    		<dependency>
    			<groupId>io.miniogroupId>
    			<artifactId>minioartifactId>
    			<version>8.0.3version>
    		dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5

    注意:这个依赖很容易和HTTP请求的依赖产生依赖冲突的问题
    可以通过添加dependencyManagement来解决这类问题,还有依赖的顺序也要注意
    这里以okhttps来举例

    		
    		<dependency>
    			<groupId>io.miniogroupId>
    			<artifactId>minioartifactId>
    			<version>8.0.3version>
    		dependency>
    
    		
    		<dependency>
    		     <groupId>com.ejlchinagroupId>
    		     <artifactId>okhttpsartifactId>
    			<version>3.5.2version>
    		dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    	<dependencyManagement>
    		<dependencies>
    			<dependency>
    				<groupId>com.squareup.okhttp3groupId>
    				<artifactId>okhttpartifactId>
    				<version>3.14.4version>
    			dependency>
    		dependencies>
    	dependencyManagement>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    3.编写配置文件

    因为minio的配置是需要我们自己来读取的,所以名称无所谓,但还是应该尽量规范一些
    此处,我们以yml格式为例

    minio:
        endpoint: http://192.168.200.128:9000 #地址
        accessKey: admin  	#用户名
        secretKey: admin123 #密码
        bucketName: application #桶
        downloadURL: http://192.168.0.119:9000/minio/download/ #下载地址
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    4.编写minio的配置类

    import io.minio.MinioClient;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.stereotype.Component;
    
    @Configuration
    @Component
    public class MinIOClientConfig {
        @Value("${minio.accessKey}")
        private String accessKey;
        @Value("${minio.endpoint}")
        private String endpoint;
        @Value("${minio.secretKey}")
        private String secretKey;
    
        @Bean
        public MinioClient minioClient(){
            return MinioClient.builder()
                    .endpoint(endpoint)
                    .credentials(accessKey, secretKey)
                    .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

    这一步完成后,可以启动项目测试一下,如果没有报错,就说明minio连接成功了

    5.通过minio存储静态资源

    先编写一个返回类,已经有的话,根据情况改返回的结构就行
    用到的依赖有lombokswagger,可以根据需求调整

    状态码:

    public interface ResultCode {
        Integer SUCCESS = 200;
        Integer ERROR = 500;
    }
    
    • 1
    • 2
    • 3
    • 4

    返回类:

    import io.swagger.annotations.ApiModelProperty;
    import lombok.Data;
    
    import java.util.HashMap;
    import java.util.Map;
    
    @Data
    public class R {
    
        @ApiModelProperty(value = "是否成功")
        private Boolean success;
    
        @ApiModelProperty(value = "返回码")
        private Integer code;
    
        @ApiModelProperty(value = "返回消息")
        private String message;
    
        @ApiModelProperty(value = "返回数据")
        private Map<String, Object> data = new HashMap<String, Object>();
    
        private R(){}
    
        public static R ok(){
            R r = new R();
            r.setSuccess(true);
            r.setCode(ResultCode.SUCCESS);
            r.setMessage("成功");
            return r;
        }
    
        public static R error(){
            R r = new R();
            r.setSuccess(false);
            r.setCode(ResultCode.ERROR);
            r.setMessage("失败");
            return r;
        }
    
        public R success(Boolean success){
            this.setSuccess(success);
            return this;
        }
    
        public R message(String message){
            this.setMessage(message);
            return this;
        }
    
        public R code(Integer code){
            this.setCode(code);
            return this;
        }
    
        public R data(String key, Object value){
            this.data.put(key, value);
            return this;
        }
    
        public R data(Map<String, Object> map){
            this.setData(map);
            return this;
        }
    }
    
    • 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

    编写minio的Controller类

    import io.minio.*;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.util.FastByteArrayOutputStream;
    import org.springframework.web.bind.annotation.*;
    import org.springframework.web.multipart.MultipartFile;
    
    import javax.annotation.Resource;
    import javax.servlet.ServletOutputStream;
    import javax.servlet.http.HttpServletResponse;
    import java.util.Objects;
    import java.util.UUID;
    
    @CrossOrigin
    @RestController
    @RequestMapping("minio")
    public class MinIOController {
        @Resource
        private MinioClient minioClient;
    
        /*
        * 存哪个桶
        * */
        @Value("${minio.bucketName}")
        private String bucketName;
    
    	//下载文件的路径
        @Value("${minio.downloadURL}")
        private String downloadURL;
    
        /*
        * 获取文件名称
        * */
        public String getFileName(String name){
            String[] split = name.split("\\.");
            //随机文件名称
            return UUID.randomUUID() + "." + split[split.length-1];
        }
    
        /*
        * 文件上传
        * */
        @PostMapping("/upload")
        public R upload(MultipartFile file){
            try {
    
                String fileName = getFileName(Objects.requireNonNull(file.getOriginalFilename()));
                PutObjectArgs objectArgs = PutObjectArgs.builder().object(fileName)
                        .bucket(bucketName)
                        .contentType(file.getContentType())
                        .stream(file.getInputStream(),file.getSize(),-1).build();
    
                minioClient.putObject(objectArgs);
                return R.ok().message(downloadURL + fileName);
            } catch (Exception e) {
                System.err.println(e.getMessage());
                return R.error().message(e.getMessage());
            }
        }
    
        /**
         * 下载文件
         */
        @GetMapping("/download/{filename}")
        public void download(@PathVariable String filename, HttpServletResponse res){
    
            GetObjectArgs objectArgs = GetObjectArgs.builder().bucket(bucketName)
                    .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) {
                System.err.println(e.getMessage());
            }
        }
    
        /**
         * 删除文件
         *
         * @param fileName 文件路径
         * @return
         */
        @DeleteMapping("/deleteFile/{fileName}")
        public R deleteFile(@PathVariable("fileName") String fileName) {
            try {
                minioClient.removeObject(RemoveObjectArgs.builder().bucket(bucketName).object(fileName).build());
            } catch (Exception e){
                System.err.println(e.getMessage());
                return R.error();
            }
            return R.ok();
        }
    
    }
    
    • 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

    打开swagger测试一下,也可以用其他工具

    在这里插入图片描述
    接口会返回下载浏览的路径
    在这里插入图片描述
    成功

  • 相关阅读:
    spring boot —— Spring Security定制权限管理
    Android Gradle 学习笔记(一)概述
    移动端日期控件rolldate
    前端必须知道的调试工具
    【k8s】(五)kubernetes1.29.4离线部署之-初始化第一个控制平面
    两万字带你认识黑客在kali中使用的工具
    leetcode刷题:动态规划09(最后一块石头的重量 II)
    【黑马程序员JVM学习笔记】04.类加载与字节码技术
    [集群聊天项目] muduo网络库
    web3.0学习入门7:深入学习Web3.0
  • 原文地址:https://blog.csdn.net/WindNolose/article/details/125978273