IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> Java知识库 -> 深入浅出Spring Boot整合minio -> 正文阅读

[Java知识库]深入浅出Spring Boot整合minio

为什么用 minio ,因为 oss 收费。

minio 官网

maven minio

最新版依赖

        <!-- https://mvnrepository.com/artifact/io.minio/minio -->
        <dependency>
            <groupId>io.minio</groupId>
            <artifactId>minio</artifactId>
            <version>8.4.5</version>
        </dependency>

如果只添加minio依赖启动项目大概率会碰到如下的报错信息

***************************
APPLICATION FAILED TO START
***************************

Description:

An attempt was made to call a method that does not exist. The attempt was made from the following location:

    io.minio.S3Base.<clinit>(S3Base.java:104)

The following method did not exist:

    okhttp3.RequestBody.create([BLokhttp3/MediaType;)Lokhttp3/RequestBody;

The method's class, okhttp3.RequestBody, is available from the following locations:

    jar:file:/D:/maven/repository/com/squareup/okhttp3/okhttp/3.14.4/okhttp-3.14.4.jar!/okhttp3/RequestBody.class

The class hierarchy was loaded from the following locations:

    okhttp3.RequestBody: file:/D:/maven/repository/com/squareup/okhttp3/okhttp/3.14.4/okhttp-3.14.4.jar


Action:

Correct the classpath of your application so that it contains a single, compatible version of okhttp3.RequestBody


进程已结束,退出代码为 1

从 io.minio.S3Base.(S3Base.java:104) 这一行点进去可以看到错误原因。

  static {
    try {
      RequestBody.create(new byte[] {}, null);
    } catch (NoSuchMethodError ex) {
      throw new RuntimeException("Unsupported OkHttp library found. Must use okhttp >= 4.8.1", ex);
    }
  }

pom minio 依赖点进去可以找到 okhttp的依赖

在这里插入图片描述
这里已经定义了 4.10.0版本,为什么到了外面不生效呢 ?

我们找到 spring-boot-starter-parent 依赖搜索 okhttp

在这里插入图片描述
发现没有结果,于是进入到 spring-boot-dependencies 中搜索 okhttp
在这里插入图片描述
我们来约束一下版本

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>com.squareup.okhttp3</groupId>
                <artifactId>okhttp</artifactId>
                <version>4.10.0</version>
            </dependency>
        </dependencies>
    </dependencyManagement>

可以看到版本已经成功使用 4.10.0
在这里插入图片描述
第二种方法

        <!-- https://mvnrepository.com/artifact/io.minio/minio -->
        <dependency>
            <groupId>io.minio</groupId>
            <artifactId>minio</artifactId>
            <version>8.4.5</version>
            <exclusions>
                <exclusion>
                    <groupId>com.squareup.okhttp3</groupId>
                    <artifactId>okhttp</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>4.10.0</version>
        </dependency>

使用

在 yml 定义几个配置

minio:
  enable: true
  endpoint: 127.0.0.1:9000
  accessKey: account
  secretKey: password
  bucketName: mkdir1

定义一个config来读取yml配置

@Configuration
public class MinIoClientConfig {

    private final static Logger logger = LoggerFactory.getLogger(MinIoClientConfig.class);

    @Value("${minio.endpoint}")
    private String endpoint;

    @Value("${minio.accessKey}")
    private String accessKey;

    @Value("${minio.secretKey}")
    private String secretKey;

    @Value("${minio.enable}")
    private boolean enable;

    @Value("${minio.bucketName}")
    private String bucketName;

    @Bean
    public MinioClient minioClient() {
        if (enable) {
            MinioClient client = MinioClient.builder()
                    .endpoint(endpoint)
                    .credentials(accessKey, secretKey)
                    .build();
            //尝试链接测试
            try {
                client.listBuckets();
            } catch (Exception e) {
                logger.error("minio client error {}", e.getMessage());
                return null;
            }
            logger.info("minio client build SUCCESS");
            return client;
        }
        return null;
    }

    // 老版本
    // @Bean
    // public MinioClient minioClient() throws Exception {
    //     if (enable) {
    //         MinioClient client = new MinioClient(endpoint, accessKey, secretKey);
    //         logger.info("minio client build success ... ... ... ");
    //         return client;
    //     }
    //     return null;
    // }


    public String getEndpoint() {
        return endpoint;
    }

    public void setEndpoint(String endpoint) {
        this.endpoint = endpoint;
    }

    public String getAccessKey() {
        return accessKey;
    }

    public void setAccessKey(String accessKey) {
        this.accessKey = accessKey;
    }

    public String getSecretKey() {
        return secretKey;
    }

    public void setSecretKey(String secretKey) {
        this.secretKey = secretKey;
    }

    public boolean isEnable() {
        return enable;
    }

    public void setEnable(boolean enable) {
        this.enable = enable;
    }

    public String getBucketName() {
        return bucketName;
    }

    public void setBucketName(String bucketName) {
        this.bucketName = bucketName;
    }
}

创建bean的时候引入连接测试获取 listBuckets ,如果获取失败则提示如下效果。
在这里插入图片描述
定义上传文件工具类

@Service
public class MinioUtils {

    private final static Logger logger = LoggerFactory.getLogger(MinioUtils.class);

    @Autowired
    MinIoClientConfig clientConfig;

    @Autowired(required = false)
    MinioClient client;

    public String upload(MultipartFile file) throws Exception {
        if (client == null) {
            throw new RuntimeException("minio enable is false or connection failure ");
        }

        String saveFileName = preUpload(file, null);

        String bucketName = clientConfig.getBucketName();
        //判断桶是否存在
        BucketExistsArgs args = BucketExistsArgs.builder().bucket(bucketName).build();
        boolean exists = client.bucketExists(args);
        if (!exists) {
            //创建存储桶
            MakeBucketArgs makeBucketArgs = MakeBucketArgs.builder().bucket(bucketName).build();
            client.makeBucket(makeBucketArgs);
            //配置权限 需要手动将桶设置为公共读
            // SetBucketPolicyArgs policy = SetBucketPolicyArgs.builder().bucket(bucketName).config("null").build();
            // client.setBucketPolicy(policy);
        }
        //上传文件
        PutObjectArgs put = PutObjectArgs.builder()
                .stream(file.getInputStream(), file.getSize(), -1)
                .bucket(bucketName).object(saveFileName).build();
        ObjectWriteResponse response = client.putObject(put);
        //
        GetObjectArgs get = GetObjectArgs.builder().bucket(bucketName).object(saveFileName).build();
        GetObjectResponse getResponse = client.getObject(get);
        //
        GetPresignedObjectUrlArgs urlArg = GetPresignedObjectUrlArgs.builder()
                .bucket(bucketName).object(saveFileName).method(Method.GET).build();
        return client.getPresignedObjectUrl(urlArg).split("\\?")[0];
    }

    // 7.0 版本
    // public String upload(MultipartFile file, String saveFileName) throws Exception {
    //     if (client == null) {
    //         throw new RuntimeException("minio enable is false ");
    //     }
    //     String bucketName = clientConfig.getBucketName();
    //     //判断桶是否存在
    //     boolean exists = client.bucketExists(bucketName);
    //     if (!exists) {
    //         throw new RuntimeException("minio bucket " + bucketName + " need create  ");
    //     }
    //     //上传文件
    //     PutObjectOptions options = new PutObjectOptions(file.getSize(), -1);
    //     client.putObject(bucketName, saveFileName, file.getInputStream(), options);
    //     //获取返回url
    //     String url = client.presignedPutObject(bucketName, saveFileName).split("\\?")[0];
    //     logger.info("upload success url is {}", url);
    //     return url;
    // }

    /**
     * 处理路径和名字
     *
     * @param file
     * @return
     */
    public String preUpload(MultipartFile file, String mkdir) {
        String fileAllName = file.getOriginalFilename();
        String prefix = LocalDateTime.now().toString().replaceAll(":", "-");
        String suffix = fileAllName.substring(fileAllName.lastIndexOf("."));
        if (mkdir == null) {
            return prefix + suffix;
        }
        return mkdir + "/" + prefix + suffix;
    }
}

根据业务扩展即可

定义一个测试controller

@RestController
@RequestMapping("file")
public class FileController {

    @Autowired
    MinioUtils service;

    @PostMapping(value = "upload", headers = "content-type=multipart/form-data")
    public String upload(@RequestPart("file") MultipartFile file) throws Exception {
        return service.upload(file);
    }
}

上传效果图如下
在这里插入图片描述
关于 Buckets 需要手动将权限改为 public
在这里插入图片描述
如果是 private 生成的 url 会带有默认的 7天时间,超过会过期。
在这里插入图片描述
如果是 private 权限,生成的 url 就不要做 split 截取,否则可能会无法访问
在这里插入图片描述

  Java知识库 最新文章
计算距离春节还有多长时间
系统开发系列 之WebService(spring框架+ma
springBoot+Cache(自定义有效时间配置)
SpringBoot整合mybatis实现增删改查、分页查
spring教程
SpringBoot+Vue实现美食交流网站的设计与实
虚拟机内存结构以及虚拟机中销毁和新建对象
SpringMVC---原理
小李同学: Java如何按多个字段分组
打印票据--java
上一篇文章      下一篇文章      查看所有文章
加:2022-10-22 21:01:38  更:2022-10-22 21:06:21 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2025年3日历 -2025/3/10 18:32:28-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码