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));
}
相关推荐
二哈赛车手8 小时前
新人笔记---ApiFox的一些常见使用出错
java·笔记·spring
栗子~~8 小时前
JAVA - 二层缓存设计(本地缓冲+redis缓冲+广播所有本地缓冲失效) demo
java·redis·缓存
YDS8299 小时前
DeepSeek RAG&MCP + Agent智能体项目 —— RAG知识库的搭建和接口实现
java·ai·springboot·agent·rag·deepseek
candyTong10 小时前
Claude Code 的 Edit 工具是怎么工作的
javascript·后端·架构
未若君雅裁10 小时前
MyBatis 一级缓存、二级缓存与清理机制
java·缓存·mybatis
AI人工智能+电脑小能手10 小时前
【大白话说Java面试题 第65题】【JVM篇】第25题:谈谈对 OOM 的认识
java·开发语言·jvm
GetcharZp11 小时前
GitHub 2.4 万 Star!D2 正在重新定义程序员画图方式
后端
阿维的博客日记11 小时前
Nacos 为什么能让配置动态生效?(涉及 @RefreshScope 注解)
java·spring
雨辰AI11 小时前
SpringBoot3 + 人大金仓读写分离 + 分库分表 + 集群高可用 全栈实战
java·数据库·mysql·政务
辰海Coding12 小时前
MiniSpring框架学习-完成的 IoC 容器
java·spring boot·学习·架构