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

1.引入pom

<dependency>
    <groupId>io.awspring.cloud</groupId>
    <artifactId>spring-cloud-aws-starter-s3</artifactId>
    <version>3.0.3</version>
</dependency>
  1. 添加配置文件
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 内的有效对象名称。对象名称可以是存储桶根文件夹中的文件,也可以是存储桶内目录中的嵌套文件。

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

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界面上传文件。下一个示例演示使用资源加载器上传资源。

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.获取文件具有时效的下载地址

@Autowired
private S3Template s3Template;
@Autowired
private S3Client s3client;

public URL getfileUrl(String bucketName,String path){   
	return s3Template.createSignedGetURL(bucketName,path,Duration.ofDays(7));
}
  • 8
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值