欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

SpringBoot整合aws的示例代码

程序员文章站 2022-06-15 15:15:03
业务需求 将本地的一些文件保存到aws上 引入依赖 创建client 工具类引入依赖

业务需求

  • 将本地的一些文件保存到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 aws