SpringBoot整合aws的示例代码

 更新时间:2021年12月01日 16:43:01   作者:一个不会代码的搬砖人  
本文通过实例代码给大家介绍SpringBoot整合aws的全过程,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧

业务需求

  • 将本地的一些文件保存到aws上
  • 引入依赖
  • 创建client
  • 工具类

引入依赖

      <dependency>
           <groupId>software.amazon.awssdk</groupId>
           <artifactId>s3</artifactId>
       </dependency>
       
         <dependency>
           <groupId>com.amazonaws</groupId>
           <artifactId>aws-java-sdk-s3</artifactId>
       </dependency>
       
       <dependency>
           <groupId>com.amazonaws</groupId>
           <artifactId>aws-java-sdk-sqs</artifactId>
       </dependency>
       
       <dependency>
           <groupId>software.amazon.awssdk</groupId>
           <artifactId>sns</artifactId>
       </dependency>
       
       <dependency>
           <groupId>com.amazonaws</groupId>
           <artifactId>aws-java-sdk-cloudfront</artifactId>
       </dependency>

创建client

 private S3Client createClient() {
       AwsCredentialsProvider credentialsProvider = StaticCredentialsProvider.create(AwsBasicCredentials.create(minIoAccessKey, minIoSecretKey));

       S3Client s3 = S3Client.builder()
               .region(Region.CN_NORTHWEST_1)
               .credentialsProvider(credentialsProvider)
               .endpointOverride(URI.create(minIoUrl))
               .build();

       return s3;
   }

aws工具类

public class MinioOperate  {


   private String minIoAccessKey;
   private String minIoSecretKey;
   private String minIoUrl;

   public MinioOperate() {
   }

   public MinioOperate(String minIoAccessKey, String minIoSecretKey, String minIoUrl) {
       this.minIoAccessKey = minIoAccessKey;
       this.minIoSecretKey = minIoSecretKey;
       this.minIoUrl = minIoUrl;
   }

#创建aws的客户端
   private S3Client createClient() {
       AwsCredentialsProvider credentialsProvider = StaticCredentialsProvider.create(AwsBasicCredentials.create(minIoAccessKey, minIoSecretKey));

       S3Client s3 = S3Client.builder()
               .region(Region.CN_NORTHWEST_1)
               .credentialsProvider(credentialsProvider)
               .endpointOverride(URI.create(minIoUrl))
               .build();

       return s3;
   }
//    public String generatePresignedUrl(String bucketName, String objectKey, String acl) {
//        URL url = null;
//        try {
//            AWSStaticCredentialsProvider credentialsProvider =
//                    new AWSStaticCredentialsProvider(
//                            new BasicAWSCredentials(minIoAccessKey, minIoSecretKey));
//
//            AmazonS3ClientBuilder builder = AmazonS3ClientBuilder.standard();
//            builder.withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(minIoUrl, Regions.CN_NORTHWEST_1.getName()));
//
//            AmazonS3 s3Client = builder
//                    .withPathStyleAccessEnabled(true)
//                    .withCredentials(credentialsProvider)
//                    .build();
//
//            // Set the presigned URL to expire after one hour.
//            Date expiration = new Date();
//            long expTimeMillis = expiration.getTime();
//            expTimeMillis += 1000 * 60 * 60 * 4;
//            expiration.setTime(expTimeMillis);
//
//            // Generate the presigned URL.
//            GeneratePresignedUrlRequest generatePresignedUrlRequest =
//                    new GeneratePresignedUrlRequest(bucketName, objectKey)
//                            .withMethod(HttpMethod.GET)
//                            .withExpiration(expiration);
//
//            // set acl
//            if (!StringUtils.isEmpty(acl)) {
//                generatePresignedUrlRequest.withMethod(HttpMethod.PUT);
//                generatePresignedUrlRequest.addRequestParameter(Headers.S3_CANNED_ACL, acl);
//            }
//
//            url = s3Client.generatePresignedUrl(generatePresignedUrlRequest);
//
//        } catch (AmazonServiceException e) {
//            // The call was transmitted successfully, but Amazon S3 couldn't process
//            // it, so it returned an error response.
//            e.printStackTrace();
//        } catch (SdkClientException e) {
//            // Amazon S3 couldn't be contacted for a response, or the client
//            // couldn't parse the response from Amazon S3.
//            e.printStackTrace();
//        }
//
//        if (StringUtils.isEmpty(url)) {
//            return null;
//        }
//        return url.toString();
//    }
  

#获取所有的对象(根据桶和前缀)
   public List<S3Object> ListObjects(String bucket, String prefix) {
   S3Client s3Client = this.createClient();
    List<S3Object> contents = null;
       try {
           ListObjectsV2Request request = ListObjectsV2Request.builder().bucket(bucket).prefix(prefix).build();
           ListObjectsV2Response listObjectsV2Response = s3Client.listObjectsV2(request);
           contents = listObjectsV2Response.contents();
       } finally {
           this.closeClient(s3Client);
       }
       return contents;
   }
  
#上传对象
   public void putObject(String bucket, String key, String content) {
       S3Client s3Client = this.createClient();
        try {
           ByteBuffer byteBuffer = ByteBuffer.wrap(content.getBytes(StandardCharsets.UTF_8));
           PutObjectResponse putObjectResponse =
                   s3.putObject(PutObjectRequest.builder().bucket(bucket).key(key)
                                   .build(),
                           RequestBody.fromByteBuffer(byteBuffer));
       } finally {
           this.closeClient(s3);
       }
   }
#上传文件
   public void putFile(String filePath, String key, String bucket) {
       S3Client s3Client = this.createClient();
       File tempFile = new File(filePath);
       try {
           PutObjectResponse putObjectResponse =
                   s3Client.putObject(PutObjectRequest.builder().bucket(bucket).key(key)
                                   .build(),
                           RequestBody.fromFile(tempFile));
       } catch (Exception e) {
           e.printStackTrace();
       } finally {
           this.closeClient(s3Client);
       }
   }

#获取对象大小
   @Override
   public long getS3ObjectLength(String bucket, String key) {
    S3Client s3Client = this.createClient();
       long size = 0;
       try {
           List<S3Object> s3Objects = this.ListObjects(s3, bucket, key);
           size = s3Objects.get(0).size();
       }catch (Exception e){
           e.printStackTrace();
       }finally {
           this.closeClient(s3);
       }
       return size;
   }

   # 获取对象
   public String getObject(String bucket, String key) {
        S3Client s3Client = this.createClient();
        try {
           ResponseBytes<GetObjectResponse> responseResponseBytes = s3.getObject(GetObjectRequest.builder().bucket(bucket).key(key).build(),
                   ResponseTransformer.toBytes());         # ResponseTransformer.toBytes()	将响应转换为二进制流
           return this.decode(responseResponseBytes.asByteBuffer());
       } finally {
           this.closeClient(s3);
       }
   }

# 获取对象的流
   @Override
   public InputStream getInputStream(String bucket, String key) {
       S3Client s3Client = this.createClient();
       try {
           ResponseBytes<GetObjectResponse> responseResponseBytes = s3.getObject(GetObjectRequest.builder().bucket(bucket).key(key).build(),
                   ResponseTransformer.toBytes());
           return responseResponseBytes.asInputStream();
       } finally {
           this.closeClient(s3);
       }
   }

#删除对象
   public void deleteObject(String bucket, String key) {
    S3Client s3Client = this.createClient();
     try {
           DeleteObjectRequest deleteObjectRequest = DeleteObjectRequest.builder().bucket(bucket).key(key).build();
           DeleteObjectResponse deleteObjectResponse = s3.deleteObject(deleteObjectRequest);
       } catch (Exception e) {
           e.printStackTrace();
       } finally {
           this.closeClient(s3);
       }
   }
#批量删除对象
   public void deleteObjects(List<String> buckets, String key) {
        S3Client s3Client = this.createClient();
        try {
           String prefix = key.substring(0, key.lastIndexOf(File.separator));
           for (String bucket : buckets) {
               ListObjectsRequest listObjectsRequest = ListObjectsRequest.builder().bucket(bucket).prefix(prefix).build();
               ListObjectsResponse listObjectsResponse = s3.listObjects(listObjectsRequest);
               List<S3Object> contents = listObjectsResponse.contents();
               for (S3Object content : contents) {
                   String objectKey = content.key();
                   this.deleteObject(s3, bucket, objectKey);
               }
               this.deleteObject(s3, bucket, prefix);
           }
       } finally {
           this.closeClient(s3);
       }
   }

}

 public String decode(ByteBuffer byteBuffer) {
       Charset charset = StandardCharsets.UTF_8;
       return charset.decode(byteBuffer).toString();
   }

其中 minIoAccessKey,minIoSecretKey, minIoUrl;分别对应账号、密码、请求地址。需要对应自己的相关信息。

到此这篇关于SpringBoot整合aws的文章就介绍到这了,更多相关SpringBoot整合aws内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • SpringBoot Admin健康检查功能的实现

    SpringBoot Admin健康检查功能的实现

    admin主要就是告诉运维人员,服务出现异常,然后进行通知(微信、邮件、短信、钉钉等)可以非常快速通知到运维人员,相当报警功能,接下来通过本文给大家介绍SpringBoot Admin健康检查的相关知识,一起看看吧
    2021-06-06
  • java GUI实现五子棋游戏

    java GUI实现五子棋游戏

    这篇文章主要为大家详细介绍了java GUI实现五子棋游戏,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2020-02-02
  • Java接口返回省市区树形结构的实现

    Java接口返回省市区树形结构的实现

    本文主要介绍了Java接口返回省市区树形结构的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-01-01
  • java后端调用第三方接口返回图片流给前端的具体代码实现

    java后端调用第三方接口返回图片流给前端的具体代码实现

    在前后端分离的开发中,经常会遇到需要从后端返回图片流给前端的情况,下面这篇文章主要给大家介绍了关于java后端调用第三方接口返回图片流给前端的具体代码实现,需要的朋友可以参考下
    2024-02-02
  • java中获取当前服务器的Ip地址的方法

    java中获取当前服务器的Ip地址的方法

    本篇文章主要介绍了java中获取当前服务器的Ip地址的方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-02-02
  • Spring中IOC和AOP的深入讲解

    Spring中IOC和AOP的深入讲解

    这篇文章主要给大家介绍了关于Spring中IOC和AOP的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2018-12-12
  • Java泛型最全知识总结

    Java泛型最全知识总结

    面试被问到Java泛型怎么办,有了这篇文章,让你直接保送,文中有非常详细的知识总结及相关代码示例,需要的朋友可以参考下
    2021-06-06
  • Springboot FeignClient调用Method has too many Body parameters解决

    Springboot FeignClient调用Method has too m

    本文主要介绍了Springboot FeignClient微服务间调用Method has too many Body parameters 解决,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2021-12-12
  • spring AOP定义AfterThrowing增加处理实例分析

    spring AOP定义AfterThrowing增加处理实例分析

    这篇文章主要介绍了spring AOP定义AfterThrowing增加处理,结合实例形式分析了spring面向切面AOP定义AfterThrowing相关实现步骤与操作技巧,需要的朋友可以参考下
    2020-01-01
  • springboot读取配置文件中的参数具体步骤

    springboot读取配置文件中的参数具体步骤

    在本篇文章里小编给大家分享了关于springboot读取配置文件中的参数的相关知识点内容,有需要的朋友们跟着学习下。
    2019-06-06

最新评论