任何人都可以指出 S3 中是否有 API 可以根据模式匹配从 S3 存储桶中删除密钥?
我能做的一种方法是:
- 列出存储桶中的所有键
- 通过 java regex 匹配它们
- 然后获得所需的结果集。
是否有任何内置API?
任何人都可以指出 S3 中是否有 API 可以根据模式匹配从 S3 存储桶中删除密钥?
我能做的一种方法是:
是否有任何内置API?
根据我的解决方案,我只是发布代码,以便它可能对寻找相同场景的人有用:
/**
* Delete keys/objects from buckets with matching prefix
* @param bucket
* Bucket in which delete operation is performed
* @param prefix
* String to match the pattern on keys.
* @return
*/
@Override
public void deleteFilesInS3(String bucket, String prefix) throws IOException {
try{
List<KeyVersion> keys = listAllKeysWithPrefix(bucket, prefix);
DeleteObjectsRequest multiObjectDeleteRequest = new DeleteObjectsRequest(bucket);
multiObjectDeleteRequest.setKeys(keys);
s3EncryptionClient.deleteObjects(multiObjectDeleteRequest);
}catch(MultiObjectDeleteException e){
throw new RuntimeException(String.format("Failed to delete files with prefix : %s from bucket : %s ",prefix,bucket),e);
}catch(AmazonServiceException ase){
throw new AmazonServiceException(String.format("Failed to delete files with prefix : %s from bucket : %s ",prefix,bucket),ase);
}catch(AmazonClientException ace){
throw new AmazonClientException(String.format("Failed to delete files with prefix : %s from bucket : %s ",prefix,bucket),ace);
}
}
/**
* Lists all the keys matching the prefix in the given bucket.
* @param bucket
* Bucket to search keys
* @param prefix
* String to match the pattern on keys.
* @return
*/
@Override
public List<KeyVersion> listAllKeysWithPrefix(String bucket,String prefix){
List<KeyVersion> keys = new ArrayList<KeyVersion>();
try{
ListObjectsRequest listObjectsRequest = new ListObjectsRequest().withBucketName(bucket).withPrefix(prefix);
ObjectListing objectListing = null;
do{
objectListing = s3EncryptionClient.listObjects(listObjectsRequest);
for(S3ObjectSummary objectSummary : objectListing.getObjectSummaries()){
keys.add(new KeyVersion(objectSummary.getKey()));
}
listObjectsRequest.setMarker(objectListing.getNextMarker());
}while(objectListing.isTruncated());
}catch(AmazonServiceException ase){
throw new AmazonServiceException(String.format("Failed to list files with prefix : %s from bucket : %s ",prefix,bucket),ase);
}catch(AmazonClientException ace){
throw new AmazonClientException(String.format("Failed to delete files with prefix : %s from bucket : %s ",prefix,bucket),ace);
}catch(Exception e){
throw new RuntimeException(String.format("Failed to delete files with prefix : %s from bucket : %s ",prefix,bucket),e);
}
return keys;
}