spring boot 3.0如何优雅的使用s3协议连接minio

1.引入pom

xml 复制代码
<dependency>
    <groupId>io.awspring.cloud</groupId>
    <artifactId>spring-cloud-aws-starter-s3</artifactId>
    <version>3.0.3</version>
</dependency>
  1. 添加配置文件
yml 复制代码
spring:
  cloud:
    aws:
      credentials:
        access-key: xxxxx
        secret-key:xxxxx
      s3:
        endpoint: http://xxxxx
      region:
        static: us-east-1  #这里必须要填一个不然会报错
  1. 下载文件
    可以通过使用s3协议引用 Amazon S3 存储桶和存储桶内的对象来下载文件。典型的模式是s3:///,bucket 是全局唯一的bucket 名称,object 是bucket 内的有效对象名称。对象名称可以是存储桶根文件夹中的文件,也可以是存储桶内目录中的嵌套文件。

下一个示例演示如何使用资源加载器加载不同的资源。

java 复制代码
public class SimpleResourceLoadingBean {

    @Autowired
    private ResourceLoader resourceLoader;

    public void resourceLoadingMethod() throws IOException {
        Resource resource = this.resourceLoader.getResource("s3://myBucket/rootFile.log");
        Resource secondResource = this.resourceLoader.getResource("s3://myBucket/rootFolder/subFile");

        InputStream inputStream = resource.getInputStream();
        //read file
    }
}

4.上传文件

从 Spring Framework 3.1 开始,资源加载器也可以用来上传带有org.springframework.core.io.WritableResource 接口的文件,这是接口的特殊化org.springframework.core.io.ResourceLoader。客户端可以使用该WritableResource界面上传文件。下一个示例演示使用资源加载器上传资源。

java 复制代码
public class SimpleResourceLoadingBean {

    @Autowired
    private ResourceLoader resourceLoader;

    public void writeResource() throws IOException {
        Resource resource = this.resourceLoader.getResource("s3://myBucket/rootFile.log");
        WritableResource writableResource = (WritableResource) resource;
        try (OutputStream outputStream = writableResource.getOutputStream()) {
            outputStream.write("test".getBytes());
        }
    }
}

5.获取文件具有时效的下载地址

java 复制代码
@Autowired
private S3Template s3Template;
@Autowired
private S3Client s3client;

public URL getfileUrl(String bucketName,String path){   
	return s3Template.createSignedGetURL(bucketName,path,Duration.ofDays(7));
}
相关推荐
__zRainy__19 分钟前
Node系列 · ORM:Sequelize 简介
数据库·后端·node.js
AskHarries1 小时前
OpenClaw 如何查看历史对话和响应时间?
后端
n8n1 小时前
Spring Boot 3.2+ 新特性、Spring AI 核心架构与 API Key 安全管理技术文档
后端
古法安卓1 小时前
Android-epoll原理详解
android·java·android studio
fireworks991 小时前
接口鉴权(401与403)
java·后端
wear工程师1 小时前
线程池里的异常去哪了?execute 和 submit 不是一回事
java
n8n1 小时前
Java 21 虚拟线程(Virtual Threads)
后端
孔明click331 小时前
别人绕过我的网关直接调用资源服务怎么办?使用 Sa-Token 解决:网关转发鉴权、RPC调用鉴权
java·sa-token·springboot·权限·权限认证
吴声子夜歌1 小时前
Java面试——设计模式(一)
java·设计模式·面试
Csvn2 小时前
🐍 Day 5: Python 函数详解 — 参数、作用域与一等公民
人工智能·后端