SpringBoot整合亚马逊S3

一、参考项

AWS S3(官网): Amazon S3 - 亚马逊云科技对象存储_云存储服务-亚马逊云科技中国区域
AWS SDK for Java(官网):Setting up the AWS SDK for Java 2.x - AWS SDK for Java

 二、效果展示

三、引入Pom文件

<!-- https://mvnrepository.com/artifact/com.amazonaws/aws-java-sdk-s3 -->
<dependency>
  <groupId>com.amazonaws</groupId>
  <artifactId>aws-java-sdk-s3</artifactId>
  <version>1.11.803</version>
</dependency>
<dependency>
  <groupId>com.amazonaws</groupId>
  <artifactId>aws-java-sdk-sts</artifactId>
  <version>1.11.803</version>
</dependency>
<dependency>
  <groupId>com.amazonaws</groupId>
  <artifactId>aws-java-sdk-core</artifactId>
  <version>1.11.803</version>
</dependency>

二、定义抽象类

public abstract class BaseObjectStorage {

    /**
     * 上传文件
     *
     * @param pathAndName
     * @param file
     */
    public abstract void upload(String pathAndName, File file);

    /**
     * 授权
     *
     * @param pathAndName
     * @param time
     * @return
     */
    public abstract String authorize(String pathAndName, long time);

    /**
     * 授权(路径全)
     *
     * @param pathAndName
     * @param time
     * @return
     */
    public abstract String authorizeAllName(String pathAndName, long time);

    /**
     * 临时上传文件授权
     *
     * @param dir
     * @return
     */
    public abstract Map<String, Object> tokens(String dir);

    /**
     * 删除文件
     *
     * @param pathAndName
     */
    public abstract void deleteFile(String pathAndName);

}

三、AWS实现类

package cn.xhh.core.objectstorage;

import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.client.builder.AwsClientBuilder.EndpointConfiguration;
import com.amazonaws.services.s3.AmazonS3;

import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.CannedAccessControlList;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.securitytoken.AWSSecurityTokenService;
import com.amazonaws.services.securitytoken.AWSSecurityTokenServiceAsyncClientBuilder;
import com.amazonaws.services.securitytoken.model.Credentials;
import com.amazonaws.services.securitytoken.model.GetFederationTokenRequest;
import com.amazonaws.services.securitytoken.model.GetFederationTokenResult;
import com.google.common.collect.Maps;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.io.File;
import java.net.URL;
import java.util.Date;
import java.util.Map;

/**
 * s3cloud上传文件
 */
@Component
@Slf4j
public class S3ObjectStorage extends BaseObjectStorage {


    @Data
    @Component
    @ConfigurationProperties(prefix = "s3")
    public static class OssInfo {
        private String host;
        private String endpoint;
        private String accessKeyId;
        private String accessKeySecret;
        private String bucketName;
        private String rootDirectory;
        private String stsEndpoint;
        private String region;
    }

    @Autowired
    private OssInfo ossInfo;

    @Override
    public void upload(String pathAndName, File file) {
        AWSStaticCredentialsProvider credential = new AWSStaticCredentialsProvider(new BasicAWSCredentials(ossInfo.accessKeyId, ossInfo.accessKeySecret));
        EndpointConfiguration endpointConfiguration = new EndpointConfiguration(ossInfo.endpoint, null);
        AmazonS3 s3 = AmazonS3ClientBuilder.standard().withCredentials(credential).withEndpointConfiguration(endpointConfiguration).build();
        try {
            String bucketPath = ossInfo.bucketName + "/" + ossInfo.rootDirectory;
            s3.putObject(new PutObjectRequest(bucketPath, pathAndName, file)
                    .withCannedAcl(CannedAccessControlList.PublicRead));
            log.info("===s3===上传文件记录:成功");
        } catch (AmazonServiceException ase) {
            log.error("===s3===文件上传服务端异常:", ase);
        } catch (AmazonClientException ace) {
            log.error("===s3===文件上传客户端异常:", ace);
        } finally {
            s3.shutdown();
        }
    }

    @Override
    public String authorize(String pathAndName, long time) {
        AWSStaticCredentialsProvider credential = new AWSStaticCredentialsProvider(new BasicAWSCredentials(ossInfo.accessKeyId, ossInfo.accessKeySecret));
        EndpointConfiguration endpointConfiguration = new EndpointConfiguration(ossInfo.endpoint, null);
        AmazonS3 s3 = AmazonS3ClientBuilder.standard().withCredentials(credential).withEndpointConfiguration(endpointConfiguration).build();
        try {
            Date expiration = new Date(System.currentTimeMillis() + time);
            URL url = s3.generatePresignedUrl(ossInfo.bucketName, ossInfo.rootDirectory + "/" + pathAndName, expiration);
            String resultUrl = url.toString();
            log.info("===s3===文件上传客户端返回url:{}", resultUrl);
            resultUrl = resultUrl.substring(0, resultUrl.indexOf("?"));
            resultUrl = resultUrl.replaceAll(ossInfo.host, ossInfo.endpoint);
            log.info("===s3===文件上传客户端返回url:{}", resultUrl);
            return resultUrl;
        } finally {
            s3.shutdown();
        }
    }

    @Override
    public String authorizeAllName(String pathAndName, long time) {
        AWSStaticCredentialsProvider credential = new AWSStaticCredentialsProvider(new BasicAWSCredentials(ossInfo.accessKeyId, ossInfo.accessKeySecret));
        EndpointConfiguration endpointConfiguration = new EndpointConfiguration(ossInfo.endpoint, null);
        AmazonS3 s3 = AmazonS3ClientBuilder.standard().withCredentials(credential).withEndpointConfiguration(endpointConfiguration).build();
        try {
            Date expiration = new Date(System.currentTimeMillis() + time);
            URL url = s3.generatePresignedUrl(ossInfo.bucketName, pathAndName, expiration);
            String resultUrl = url.toString();
            resultUrl = resultUrl.replaceAll(ossInfo.host, ossInfo.endpoint);
            log.info("===s3==========authorizeAllName,S3文件上传客户端返回url:{}", resultUrl);
            return resultUrl;
        } finally {
            s3.shutdown();
        }
    }

    @Override
    public Map<String, Object> tokens(String dir) {
        Map<String, Object> result = null;
        AWSSecurityTokenService stsClient = null;
        try {
            result = Maps.newHashMap();
            AWSStaticCredentialsProvider credential = new AWSStaticCredentialsProvider(new BasicAWSCredentials(ossInfo.accessKeyId, ossInfo.accessKeySecret));
            EndpointConfiguration endpointConfiguration = new EndpointConfiguration(ossInfo.stsEndpoint, null);
            stsClient = AWSSecurityTokenServiceAsyncClientBuilder.standard().withCredentials(credential)
                    .withEndpointConfiguration(endpointConfiguration).build();
            GetFederationTokenRequest request = new GetFederationTokenRequest().withName("Bob")
                    .withPolicy("{\"Version\":\"2012-10-17\",\"Statement\":[{\"Sid\":\"Sid1\",\"Effect\":\"Allow\",\"Action\":[\"s3:*\"],\"Resource\":[\"*\"]}]}")
                    .withDurationSeconds(3600);
            GetFederationTokenResult response = stsClient.getFederationToken(request);
            Credentials tempCredentials = response.getCredentials();

 /*
            // TODO 备份获取Token
            stsClient = AWSSecurityTokenServiceClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials(ossInfo.accessKeyId, ossInfo.accessKeySecret))).withRegion(ossInfo.region).build();
            //获取sessionToken实体
            GetSessionTokenRequest getSessionTokenRequest = new GetSessionTokenRequest().withDurationSeconds(3000);
            //创建请求
            Credentials tempCredentials = stsClient.getSessionToken(getSessionTokenRequest).getCredentials();
*/

            result.put("storeType", "s3");
            result.put("accessKeyId", tempCredentials.getAccessKeyId());
            result.put("sessionToken", tempCredentials.getSessionToken());
            result.put("secretKey", tempCredentials.getSecretAccessKey());
            result.put("expire", tempCredentials.getExpiration());
            result.put("dir", dir);
            result.put("bucketName", ossInfo.bucketName);
            result.put("region", ossInfo.region);
            result.put("host", "https://" + ossInfo.endpoint + "/" + ossInfo.bucketName);
            log.info("===s3===上传文件记录:accessKeyId:{},sessionToken:{}", tempCredentials.getAccessKeyId(), tempCredentials.getSessionToken());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != stsClient) {
                stsClient.shutdown();
            }
        }
        return result;

    }

    @Override
    public void deleteFile(String pathAndName) {
        AWSStaticCredentialsProvider credential = new AWSStaticCredentialsProvider(new BasicAWSCredentials(ossInfo.accessKeyId, ossInfo.accessKeySecret));
        EndpointConfiguration endpointConfiguration = new EndpointConfiguration(ossInfo.endpoint, null);
        AmazonS3 s3 = AmazonS3ClientBuilder.standard().withCredentials(credential).withEndpointConfiguration(endpointConfiguration).build();
        try {
            s3.deleteObject(ossInfo.bucketName, ossInfo.bucketName + pathAndName);
        } finally {
            s3.shutdown();
        }
    }


}

四、application配置文件

objectstorage.type: s3
s3:
  endpoint: s3.us-east-1.amazonaws.com
  access-key-id: 您的公钥AKIAXZXXXX2GMAJVNUS
  access-key-secret: 您的秘钥CGNF3NQl4d0zvDuGEGuBsW9OS
  bucket-name: xhh-test-bucket
  root-directory: xhh/export
  region: us-east-1

  • 2
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Spring Boot是一个开发框架,可以用于快速、简单地创建基于Java的Web应用程序。而S3 (Simple Storage Service) 是亚马逊提供的一种存储服务,可以轻松地存储和检索大量数据。 要在Spring Boot项目中整合S3,首先需要添加相关依赖。可以通过在pom.xml文件中添加Amazon S3 SDK的依赖来实现。然后,在应用程序的配置文件中添加S3相关的配置,包括访问密钥、区域等信息。 接下来,可以创建一个S3Service类来封装对S3的操作。在该类中,可以使用Amazon S3 SDK提供的API来实现上传、下载、删除文件等功能。例如,可以使用putObject方法将文件上传到S3存储桶中,使用getObject方法从S3中获取文件,使用deleteObject方法删除文件等。 在Spring Boot的控制器中,可以通过注入S3Service类来使用S3的功能。例如,可以编写一个上传文件的接口,接收文件并调用S3Service的方法将文件上传到S3中。同样,可以编写下载文件的接口,接收文件名并调用S3Service的方法从S3中获取文件并返回给客户端。 总的来说,Spring Boot整合S3可以通过添加依赖、配置S3信息、编写S3Service类来实现对S3存储服务的使用。这样就可以在Spring Boot应用程序中轻松地实现文件的上传、下载、删除等功能。现在,您可以在Spring Boot项目中集成S3以便处理文件存储需求。 ### 回答2: springboot 是一个开源的Java框架,用于快速构建基于Java的企业级应用程序。而S3亚马逊AWS提供的一种对象存储服务,它可以方便地存储和访问大量的数据。 要在springboot整合S3,可以按照以下步骤进行: 1. 引入依赖:在pom.xml文件中,添加对AWSSDK的依赖。可以使用Maven或者Gradle构建工具来管理依赖。 2. 配置S3客户端:在application.properties或者application.yml文件中,配置S3客户端的相关信息,包括访问密钥、区域、桶名称等。 3. 创建S3服务类:创建一个S3Service类作为服务层的组件,使用@Autowired注解注入S3客户端实例,并编写相应的方法来操作S3服务,例如上传文件、下载文件、删除文件等。 4. 编写Controller类:创建一个Controller类,并使用@Autowired注解注入S3Service实例。在Controller类中,编写相应的API接口方法,调用S3Service的方法来实现文件的上传、下载和删除等功能。 通过上述步骤,就可以在springboot项目中成功整合S3。你可以通过调用相应的API接口来实现文件的上传、下载和删除等操作。同时,springboot的优秀特性也可以帮助你更好地管理和处理S3服务中的数据。 ### 回答3: Spring Boot是一个基于Spring框架的快速开发框架,而S3亚马逊提供的一种用于存储和检索大型文件的云服务。下面我将介绍如何在Spring Boot项目中整合S3。 第一步是添加S3相关的依赖。在pom.xml文件中,添加Amazon S3 SDK的依赖项。使用Maven可以很方便地实现这一步骤。 第二步是配置S3的访问凭证和连接信息。可以将这些信息配置在配置文件中,如application.properties或application.yml。配置信息包括访问秘钥、秘钥ID、存储桶名称、区域等信息。 第三步是创建S3客户端对象。在Spring Boot中,可以使用AmazonS3ClientBuilder来创建S3客户端对象。在创建对象时,需要提供上一步中配置的访问凭证和连接信息。 第四步是上传和下载文件。使用S3客户端对象,可以通过调用相关的API来实现文件的上传和下载操作。例如,可以使用putObject方法上传文件,使用getObject方法下载文件。 除了基本的上传和下载文件操作,还可以通过S3客户端对象来实现其他操作,如删除文件、复制文件、获取文件列表等。 最后,可以将以上代码封装在自定义的Service层中,以便在业务逻辑中调用。 在整合S3之后,可以在Spring Boot项目中方便地使用S3的云存储服务,实现文件的上传、下载和管理等功能。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值