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));
}
相关推荐
xbgRS8 小时前
springboot的自动装配
java·spring boot
东风破_15 小时前
ESLint 是什么?为什么你的项目需要它?
前端·后端·代码规范
嘻哈∠※15 小时前
0061基于 SpringBoot 的投稿与稿件处理系统设计与实现
java·spring boot·后端
卷无止境15 小时前
在 awesome-fastapi 里,哪些库值得一看?
后端·python
白狐_79816 小时前
408数据结构第8章:排序②——性质对比秒杀、场景选择与外部排序
java·数据结构·算法
zander25816 小时前
LeetCode 84:柱状图中的最大矩形——单调栈如何确定左右边界
java·数据结构·算法
码匠许师傅17 小时前
【C++ 面试真题】聊聊 C++ 的拷贝构造与拷贝赋值
java·c++·面试
卷无止境17 小时前
FastAPI 的Admin面板生态
后端·python
捡田螺的小男孩18 小时前
什么是 Skill?手把手带你写一个简单有用的 Skill!
前端·后端·程序员
IT_陈寒18 小时前
Redis集群这个坑,差点让我通宵
前端·人工智能·后端