广告
返回顶部
首页 > 资讯 > 后端开发 > Python >SpringBoot整合aws的示例代码
  • 548
分享到

SpringBoot整合aws的示例代码

2024-04-02 19:04:59 548人浏览 八月长安

Python 官方文档:入门教程 => 点击学习

摘要

业务需求 将本地的一些文件保存到aws上 引入依赖 创建client 工具类 引入依赖 <dependency>

业务需求

  • 将本地的一些文件保存到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内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: SpringBoot整合aws的示例代码

本文链接: https://www.lsjlt.com/news/158941.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • SpringBoot整合aws的示例代码
    业务需求 将本地的一些文件保存到aws上 引入依赖 创建client 工具类 引入依赖 <dependency> ...
    99+
    2022-11-12
  • SpringBoot整合SpringDataRedis的示例代码
      本文介绍下SpringBoot如何整合SpringDataRedis框架的,SpringDataRedis具体的内容在前面已经介绍过了,可自行参考。 1....
    99+
    2022-11-12
  • SpringBoot整合jersey的示例代码
    这篇文章主要从以下几个方面来介绍。简单介绍下jersey,springboot,重点介绍如何整合springboot与jersey。 什么是jersey 什么是springboot 为什么要使用springboot+jersey 如...
    99+
    2023-05-31
    springboot jersey ers
  • SpringBoot整合logback的示例代码
    Logback简介 1、logback和log4j是同一个作者,logback可以看作是log4j的升级版 2、logback分为三个模块, logback-core, logbac...
    99+
    2022-11-13
  • SpringBoot整合ShardingSphere的示例代码
    目录一、相关依赖二、Nacos数据源配置三、项目配置四、验证概要: ShardingSphere是一套开源的分布式数据库中间件解决方案组成的生态圈,它由Sharding-JDBC、S...
    99+
    2022-11-12
  • springboot 整合sentinel的示例代码
    目录1. 安装sentinel2.客户端连接1. 安装sentinel         下载地址:https://github.com/ali...
    99+
    2022-11-13
  • SpringBoot整合Liquibase的示例代码
    目录整合1整合2SpringBoot整合Liquibase虽然不难但坑还是有一点的,主要集中在配置路径相关的地方,在此记录一下整合的步骤,方便以后自己再做整合时少走弯路,当然也希望能...
    99+
    2022-11-13
  • Springboot整合kafka的示例代码
    目录1.整合kafka2.消息发送2.1发送类型2.2序列化2.3分区策略3.消息消费3.1消息组别3.2位移提交1. 整合kafka 1、引入依赖 <dependency&...
    99+
    2022-11-13
  • springboot 整合hbase的示例代码
    目录前言HBase 定义HBase 数据模型物理存储结构数据模型1、Name Space2、Region3、Row4、Column5、Time Stamp6、Cell搭建步骤1、官网...
    99+
    2022-11-13
  • SpringBoot整合JdbcTemplate的示例代码
    目录前言初始化SpringBoot项目使用IDEA创建项目导入JDBC依赖导入数据库驱动修改配置文件数据库sys_user表结构测试类代码查询sys_user表数据量查询sys_us...
    99+
    2022-11-13
  • SpringBoot整合Minio的示例代码
    SpringBoot整合Minio 进入Minio官网,下载对应的Minio版本 官网安装文档 下载完成之后,启动(windows版) minio.exe server D:\m...
    99+
    2022-12-27
    SpringBoot整合Minio SpringBoot Minio整合 SpringBoot Minio
  • SpringBoot整合ElasticSearch的示例代码
    ElasticSearch作为基于Lucene的搜索服务器,既可以作为一个独立的服务部署,也可以签入Web应用中。SpringBoot作为Spring家族的全新框架,使得使用SpringBoot开发Spring应用变得非常简单。本文要介绍如...
    99+
    2023-05-31
    spring boot elasticsearch
  • springboot整合xxl-job的示例代码
    目录关于xxl-job调度中心执行器关于xxl-job 在我看来,总体可以分为三大块: 调度中心执行器配置定时任务 调度中心 简单来讲就是 xxl-job-admin那个模块,配置:...
    99+
    2022-11-13
  • springboot整合mongodb changestream的示例代码
    目录前言Change Stream 介绍环境准备Java客户端操作changestream1、引入maven依赖2、测试类核心代码下面来看看具体的整合步骤1、引入核心依赖2、核心配置...
    99+
    2022-11-13
  • SpringBoot整合MyBatis-Plus的示例代码
    目录前言源码环境开发工具 SQL脚本 正文单工程POM文件(注意) application.properties(注意)自定义配置(注意)实体类(注意)...
    99+
    2022-11-13
  • SpringBoot示例代码整合Redis详解
    目录Redis 简介Redis 优势Redis与其他key-value存储有什么不同添加Redis依赖包配置Redis数据库连接编写Redis操作工具类测试Redis 简介 Redi...
    99+
    2022-11-13
  • SpringBoot框架整合SwaggerUI的示例代码
    整合swagger进行模块测试 注意事项:为方便SpringBoot更好的整合Swagger,需要专门放置在一个模块中(maven子工程) 创建公共模块,整合swagger,为了所有...
    99+
    2022-11-13
  • SpringBoot整合Redis管道的示例代码
    目录1. Redis 之管道(pipeline)2. SpringBoot 整合 Redis 管道实例1. Redis 之管道(pipeline) 执行一个Redis命令,Redis...
    99+
    2022-11-12
  • SpringBoot整合Shiro和Redis的示例代码
    目录1.准备工作2.编写index,login,register三个JSP3.实现User、Role、Permission三个POJO4.实现Controller、Service、D...
    99+
    2022-11-13
  • Springboot整合mqtt服务的示例代码
    首先在pom文件里引入mqtt的依赖配置 <!--mqtt--> <dependency> <g...
    99+
    2022-11-13
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作