当前位置:   article > 正文

SpringBoot整合亚马逊S3_aws-java-sdk-sts

aws-java-sdk-sts

一、参考项

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

 二、效果展示

三、引入Pom文件

  1. <!-- https://mvnrepository.com/artifact/com.amazonaws/aws-java-sdk-s3 -->
  2. <dependency>
  3. <groupId>com.amazonaws</groupId>
  4. <artifactId>aws-java-sdk-s3</artifactId>
  5. <version>1.11.803</version>
  6. </dependency>
  7. <dependency>
  8. <groupId>com.amazonaws</groupId>
  9. <artifactId>aws-java-sdk-sts</artifactId>
  10. <version>1.11.803</version>
  11. </dependency>
  12. <dependency>
  13. <groupId>com.amazonaws</groupId>
  14. <artifactId>aws-java-sdk-core</artifactId>
  15. <version>1.11.803</version>
  16. </dependency>

二、定义抽象类

  1. public abstract class BaseObjectStorage {
  2. /**
  3. * 上传文件
  4. *
  5. * @param pathAndName
  6. * @param file
  7. */
  8. public abstract void upload(String pathAndName, File file);
  9. /**
  10. * 授权
  11. *
  12. * @param pathAndName
  13. * @param time
  14. * @return
  15. */
  16. public abstract String authorize(String pathAndName, long time);
  17. /**
  18. * 授权(路径全)
  19. *
  20. * @param pathAndName
  21. * @param time
  22. * @return
  23. */
  24. public abstract String authorizeAllName(String pathAndName, long time);
  25. /**
  26. * 临时上传文件授权
  27. *
  28. * @param dir
  29. * @return
  30. */
  31. public abstract Map<String, Object> tokens(String dir);
  32. /**
  33. * 删除文件
  34. *
  35. * @param pathAndName
  36. */
  37. public abstract void deleteFile(String pathAndName);
  38. }

三、AWS实现类

  1. package cn.xhh.core.objectstorage;
  2. import com.amazonaws.AmazonClientException;
  3. import com.amazonaws.AmazonServiceException;
  4. import com.amazonaws.auth.AWSStaticCredentialsProvider;
  5. import com.amazonaws.auth.BasicAWSCredentials;
  6. import com.amazonaws.client.builder.AwsClientBuilder.EndpointConfiguration;
  7. import com.amazonaws.services.s3.AmazonS3;
  8. import com.amazonaws.services.s3.AmazonS3ClientBuilder;
  9. import com.amazonaws.services.s3.model.CannedAccessControlList;
  10. import com.amazonaws.services.s3.model.PutObjectRequest;
  11. import com.amazonaws.services.securitytoken.AWSSecurityTokenService;
  12. import com.amazonaws.services.securitytoken.AWSSecurityTokenServiceAsyncClientBuilder;
  13. import com.amazonaws.services.securitytoken.model.Credentials;
  14. import com.amazonaws.services.securitytoken.model.GetFederationTokenRequest;
  15. import com.amazonaws.services.securitytoken.model.GetFederationTokenResult;
  16. import com.google.common.collect.Maps;
  17. import lombok.Data;
  18. import lombok.extern.slf4j.Slf4j;
  19. import org.springframework.beans.factory.annotation.Autowired;
  20. import org.springframework.boot.context.properties.ConfigurationProperties;
  21. import org.springframework.stereotype.Component;
  22. import java.io.File;
  23. import java.net.URL;
  24. import java.util.Date;
  25. import java.util.Map;
  26. /**
  27. * s3cloud上传文件
  28. */
  29. @Component
  30. @Slf4j
  31. public class S3ObjectStorage extends BaseObjectStorage {
  32. @Data
  33. @Component
  34. @ConfigurationProperties(prefix = "s3")
  35. public static class OssInfo {
  36. private String host;
  37. private String endpoint;
  38. private String accessKeyId;
  39. private String accessKeySecret;
  40. private String bucketName;
  41. private String rootDirectory;
  42. private String stsEndpoint;
  43. private String region;
  44. }
  45. @Autowired
  46. private OssInfo ossInfo;
  47. @Override
  48. public void upload(String pathAndName, File file) {
  49. AWSStaticCredentialsProvider credential = new AWSStaticCredentialsProvider(new BasicAWSCredentials(ossInfo.accessKeyId, ossInfo.accessKeySecret));
  50. EndpointConfiguration endpointConfiguration = new EndpointConfiguration(ossInfo.endpoint, null);
  51. AmazonS3 s3 = AmazonS3ClientBuilder.standard().withCredentials(credential).withEndpointConfiguration(endpointConfiguration).build();
  52. try {
  53. String bucketPath = ossInfo.bucketName + "/" + ossInfo.rootDirectory;
  54. s3.putObject(new PutObjectRequest(bucketPath, pathAndName, file)
  55. .withCannedAcl(CannedAccessControlList.PublicRead));
  56. log.info("===s3===上传文件记录:成功");
  57. } catch (AmazonServiceException ase) {
  58. log.error("===s3===文件上传服务端异常:", ase);
  59. } catch (AmazonClientException ace) {
  60. log.error("===s3===文件上传客户端异常:", ace);
  61. } finally {
  62. s3.shutdown();
  63. }
  64. }
  65. @Override
  66. public String authorize(String pathAndName, long time) {
  67. AWSStaticCredentialsProvider credential = new AWSStaticCredentialsProvider(new BasicAWSCredentials(ossInfo.accessKeyId, ossInfo.accessKeySecret));
  68. EndpointConfiguration endpointConfiguration = new EndpointConfiguration(ossInfo.endpoint, null);
  69. AmazonS3 s3 = AmazonS3ClientBuilder.standard().withCredentials(credential).withEndpointConfiguration(endpointConfiguration).build();
  70. try {
  71. Date expiration = new Date(System.currentTimeMillis() + time);
  72. URL url = s3.generatePresignedUrl(ossInfo.bucketName, ossInfo.rootDirectory + "/" + pathAndName, expiration);
  73. String resultUrl = url.toString();
  74. log.info("===s3===文件上传客户端返回url:{}", resultUrl);
  75. resultUrl = resultUrl.substring(0, resultUrl.indexOf("?"));
  76. resultUrl = resultUrl.replaceAll(ossInfo.host, ossInfo.endpoint);
  77. log.info("===s3===文件上传客户端返回url:{}", resultUrl);
  78. return resultUrl;
  79. } finally {
  80. s3.shutdown();
  81. }
  82. }
  83. @Override
  84. public String authorizeAllName(String pathAndName, long time) {
  85. AWSStaticCredentialsProvider credential = new AWSStaticCredentialsProvider(new BasicAWSCredentials(ossInfo.accessKeyId, ossInfo.accessKeySecret));
  86. EndpointConfiguration endpointConfiguration = new EndpointConfiguration(ossInfo.endpoint, null);
  87. AmazonS3 s3 = AmazonS3ClientBuilder.standard().withCredentials(credential).withEndpointConfiguration(endpointConfiguration).build();
  88. try {
  89. Date expiration = new Date(System.currentTimeMillis() + time);
  90. URL url = s3.generatePresignedUrl(ossInfo.bucketName, pathAndName, expiration);
  91. String resultUrl = url.toString();
  92. resultUrl = resultUrl.replaceAll(ossInfo.host, ossInfo.endpoint);
  93. log.info("===s3==========authorizeAllName,S3文件上传客户端返回url:{}", resultUrl);
  94. return resultUrl;
  95. } finally {
  96. s3.shutdown();
  97. }
  98. }
  99. @Override
  100. public Map<String, Object> tokens(String dir) {
  101. Map<String, Object> result = null;
  102. AWSSecurityTokenService stsClient = null;
  103. try {
  104. result = Maps.newHashMap();
  105. AWSStaticCredentialsProvider credential = new AWSStaticCredentialsProvider(new BasicAWSCredentials(ossInfo.accessKeyId, ossInfo.accessKeySecret));
  106. EndpointConfiguration endpointConfiguration = new EndpointConfiguration(ossInfo.stsEndpoint, null);
  107. stsClient = AWSSecurityTokenServiceAsyncClientBuilder.standard().withCredentials(credential)
  108. .withEndpointConfiguration(endpointConfiguration).build();
  109. GetFederationTokenRequest request = new GetFederationTokenRequest().withName("Bob")
  110. .withPolicy("{\"Version\":\"2012-10-17\",\"Statement\":[{\"Sid\":\"Sid1\",\"Effect\":\"Allow\",\"Action\":[\"s3:*\"],\"Resource\":[\"*\"]}]}")
  111. .withDurationSeconds(3600);
  112. GetFederationTokenResult response = stsClient.getFederationToken(request);
  113. Credentials tempCredentials = response.getCredentials();
  114. /*
  115. // TODO 备份获取Token
  116. stsClient = AWSSecurityTokenServiceClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials(ossInfo.accessKeyId, ossInfo.accessKeySecret))).withRegion(ossInfo.region).build();
  117. //获取sessionToken实体
  118. GetSessionTokenRequest getSessionTokenRequest = new GetSessionTokenRequest().withDurationSeconds(3000);
  119. //创建请求
  120. Credentials tempCredentials = stsClient.getSessionToken(getSessionTokenRequest).getCredentials();
  121. */
  122. result.put("storeType", "s3");
  123. result.put("accessKeyId", tempCredentials.getAccessKeyId());
  124. result.put("sessionToken", tempCredentials.getSessionToken());
  125. result.put("secretKey", tempCredentials.getSecretAccessKey());
  126. result.put("expire", tempCredentials.getExpiration());
  127. result.put("dir", dir);
  128. result.put("bucketName", ossInfo.bucketName);
  129. result.put("region", ossInfo.region);
  130. result.put("host", "https://" + ossInfo.endpoint + "/" + ossInfo.bucketName);
  131. log.info("===s3===上传文件记录:accessKeyId:{},sessionToken:{}", tempCredentials.getAccessKeyId(), tempCredentials.getSessionToken());
  132. } catch (Exception e) {
  133. e.printStackTrace();
  134. } finally {
  135. if (null != stsClient) {
  136. stsClient.shutdown();
  137. }
  138. }
  139. return result;
  140. }
  141. @Override
  142. public void deleteFile(String pathAndName) {
  143. AWSStaticCredentialsProvider credential = new AWSStaticCredentialsProvider(new BasicAWSCredentials(ossInfo.accessKeyId, ossInfo.accessKeySecret));
  144. EndpointConfiguration endpointConfiguration = new EndpointConfiguration(ossInfo.endpoint, null);
  145. AmazonS3 s3 = AmazonS3ClientBuilder.standard().withCredentials(credential).withEndpointConfiguration(endpointConfiguration).build();
  146. try {
  147. s3.deleteObject(ossInfo.bucketName, ossInfo.bucketName + pathAndName);
  148. } finally {
  149. s3.shutdown();
  150. }
  151. }
  152. }

四、application配置文件

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

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop】
推荐阅读
相关标签
  

闽ICP备14008679号