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));
}
相关推荐
Conan在掘金24 分钟前
鸿蒙报错速查:arkts-strict-typing Property does not exist on type 'object',object 装函数就炸,根因 + 真解法
后端
颜酱28 分钟前
01 | 骨架搭建:FastAPI + Vue 跑通第一个 SSE 流式问答
前端·人工智能·后端
程序员cxuan1 小时前
Grok Build 被众人唾骂,结果老马把它开源了
人工智能·后端·程序员
莫逸风1 小时前
【AgentScope 2.0】 0. 学习指南
java·llm·agent·agentscope
从零开始的代码生活_1 小时前
C++ 继承详解:访问控制、对象模型、菱形继承与设计取舍
开发语言·c++·后端·学习·算法
Conan在掘金2 小时前
�鸿蒙报错速查:Cannot find name 'require',禁用 require(),根因 + 真解法
后端
隔窗听雨眠2 小时前
Spring Boot在云原生时代的编程范式革新研究
spring boot·后端·云原生
一朵小花2 小时前
记一次Docker 容器 NFS 文件写入延迟排查过程
后端
z123456789862 小时前
2026最新两款AI编程工具深度对比实测
java·数据库·ai编程
yaoxin5211233 小时前
470. Java 反射 - Member 接口与 AccessFlag
java·开发语言·python