awsClient工具类

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();
    }

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
AWS S3是亚马逊提供的一种云存储服务,可以用来存储和检索任意类型的数据,包括文本和二进制数据。在Java中,可以使用AWS SDK for Java来访问S3服务。 以下是一个简单的Java AWS S3文件服务器工具类的示例代码: ``` import com.amazonaws.AmazonClientException; import com.amazonaws.AmazonServiceException; import com.amazonaws.auth.AWSCredentials; import com.amazonaws.auth.BasicAWSCredentials; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3Client; import com.amazonaws.services.s3.model.*; import java.io.File; public class S3FileServer { private AmazonS3 s3client; public S3FileServer(String accessKey, String secretKey) { AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey); this.s3client = new AmazonS3Client(credentials); } public void uploadFile(String bucketName, String keyName, File file) { try { s3client.putObject(new PutObjectRequest(bucketName, keyName, file)); } catch (AmazonServiceException ase) { System.out.println("Caught an AmazonServiceException, which means your request made it to Amazon S3, but was rejected with an error response for some reason."); System.out.println("Error Message: " + ase.getMessage()); System.out.println("HTTP Status Code: " + ase.getStatusCode()); System.out.println("AWS Error Code: " + ase.getErrorCode()); System.out.println("Error Type: " + ase.getErrorType()); System.out.println("Request ID: " + ase.getRequestId()); } catch (AmazonClientException ace) { System.out.println("Caught an AmazonClientException, which means the client encountered a serious internal problem while trying to communicate with S3, such as not being able to access the network."); System.out.println("Error Message: " + ace.getMessage()); } } public void downloadFile(String bucketName, String keyName, File file) { try { s3client.getObject(new GetObjectRequest(bucketName, keyName), file); } catch (AmazonServiceException ase) { System.out.println("Caught an AmazonServiceException, which means your request made it to Amazon S3, but was rejected with an error response for some reason."); System.out.println("Error Message: " + ase.getMessage()); System.out.println("HTTP Status Code: " + ase.getStatusCode()); System.out.println("AWS Error Code: " + ase.getErrorCode()); System.out.println("Error Type: " + ase.getErrorType()); System.out.println("Request ID: " + ase.getRequestId()); } catch (AmazonClientException ace) { System.out.println("Caught an AmazonClientException, which means the client encountered a serious internal problem while trying to communicate with S3, such as not being able to access the network."); System.out.println("Error Message: " + ace.getMessage()); } } public void deleteFile(String bucketName, String keyName) { try { s3client.deleteObject(new DeleteObjectRequest(bucketName, keyName)); } catch (AmazonServiceException ase) { System.out.println("Caught an AmazonServiceException, which means your request made it to Amazon S3, but was rejected with an error response for some reason."); System.out.println("Error Message: " + ase.getMessage()); System.out.println("HTTP Status Code: " + ase.getStatusCode()); System.out.println("AWS Error Code: " + ase.getErrorCode()); System.out.println("Error Type: " + ase.getErrorType()); System.out.println("Request ID: " + ase.getRequestId()); } catch (AmazonClientException ace) { System.out.println("Caught an AmazonClientException, which means the client encountered a serious internal problem while trying to communicate with S3, such as not being able to access the network."); System.out.println("Error Message: " + ace.getMessage()); } } public void createBucket(String bucketName) { try { s3client.createBucket(bucketName); } catch (AmazonServiceException ase) { System.out.println("Caught an AmazonServiceException, which means your request made it to Amazon S3, but was rejected with an error response for some reason."); System.out.println("Error Message: " + ase.getMessage()); System.out.println("HTTP Status Code: " + ase.getStatusCode()); System.out.println("AWS Error Code: " + ase.getErrorCode()); System.out.println("Error Type: " + ase.getErrorType()); System.out.println("Request ID: " + ase.getRequestId()); } catch (AmazonClientException ace) { System.out.println("Caught an AmazonClientException, which means the client encountered a serious internal problem while trying to communicate with S3, such as not being able to access the network."); System.out.println("Error Message: " + ace.getMessage()); } } public void deleteBucket(String bucketName) { try { s3client.deleteBucket(bucketName); } catch (AmazonServiceException ase) { System.out.println("Caught an AmazonServiceException, which means your request made it to Amazon S3, but was rejected with an error response for some reason."); System.out.println("Error Message: " + ase.getMessage()); System.out.println("HTTP Status Code: " + ase.getStatusCode()); System.out.println("AWS Error Code: " + ase.getErrorCode()); System.out.println("Error Type: " + ase.getErrorType()); System.out.println("Request ID: " + ase.getRequestId()); } catch (AmazonClientException ace) { System.out.println("Caught an AmazonClientException, which means the client encountered a serious internal problem while trying to communicate with S3, such as not being able to access the network."); System.out.println("Error Message: " + ace.getMessage()); } } public void listBuckets() { try { for (Bucket bucket : s3client.listBuckets()) { System.out.println(bucket.getName()); } } catch (AmazonServiceException ase) { System.out.println("Caught an AmazonServiceException, which means your request made it to Amazon S3, but was rejected with an error response for some reason."); System.out.println("Error Message: " + ase.getMessage()); System.out.println("HTTP Status Code: " + ase.getStatusCode()); System.out.println("AWS Error Code: " + ase.getErrorCode()); System.out.println("Error Type: " + ase.getErrorType()); System.out.println("Request ID: " + ase.getRequestId()); } catch (AmazonClientException ace) { System.out.println("Caught an AmazonClientException, which means the client encountered a serious internal problem while trying to communicate with S3, such as not being able to access the network."); System.out.println("Error Message: " + ace.getMessage()); } } public void listObjects(String bucketName) { try { ObjectListing objectListing = s3client.listObjects(new ListObjectsRequest().withBucketName(bucketName)); for (S3ObjectSummary objectSummary : objectListing.getObjectSummaries()) { System.out.println(objectSummary.getKey()); } } catch (AmazonServiceException ase) { System.out.println("Caught an AmazonServiceException, which means your request made it to Amazon S3, but was rejected with an error response for some reason."); System.out.println("Error Message: " + ase.getMessage()); System.out.println("HTTP Status Code: " + ase.getStatusCode()); System.out.println("AWS Error Code: " + ase.getErrorCode()); System.out.println("Error Type: " + ase.getErrorType()); System.out.println("Request ID: " + ase.getRequestId()); } catch (AmazonClientException ace) { System.out.println("Caught an AmazonClientException, which means the client encountered a serious internal problem while trying to communicate with S3, such as not being able to access the network."); System.out.println("Error Message: " + ace.getMessage()); } } } ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值