OBS JAVA SDK 实践2:模拟桶删的功能(删除非空桶)
1 背景介绍
目前OBS只支持删除空桶,如果桶中有数据,需要先删除桶中所有数据(包含多版本),之后才能删除桶。下面的代码模拟桶删的功能,展示如何一步到位删除非空桶。
2 效果展示
这里桶obs-chongchong-guangzhou桶中有约2000个对象数据,多个文件夹
使用代码进行桶删后,在桶列表中已经找不到此桶
3 java代码参考
前提:
需要先下载OBS最新的JAVA SDK,参考官网链接:https://developer.huaweicloud.com/sdk?OBS,并在自己的项目中导入SDK中的JAR包。
import java.io.IOException;
import com.obs.services.ObsClient;
import com.obs.services.ObsConfiguration;
import com.obs.services.exception.ObsException;
import com.obs.services.model.DeleteObjectsRequest;
import com.obs.services.model.DeleteObjectsResult;
import com.obs.services.model.ListVersionsRequest;
import com.obs.services.model.ListVersionsResult;
import com.obs.services.model.VersionOrDeleteMarker;
public class BucketDelete {
private static ObsClient obsClient;
public static void main(String[] args) throws InterruptedException
{
try
{
String endPoint = "XXX"; // e.g "https://obs.cn-north-1.myhuaweicloud.com"
String ak = "XXX"; // 对象所属的帐户ak
String sk = "XXX"; // 对象所属的帐户sk
String bucketName = "obs-chongchong-beijing"; // 需要填写为实际的桶名
obsClient = new ObsClient(ak, sk, endPoint);
//列举桶中对象并删除
ListVersionsResult result = obsClient.listVersions(bucketName);
if(result.getVersions().length != 0)
{
ListVersionsRequest request = new ListVersionsRequest(bucketName);
// 设置每次批量删除500个对象
request.setMaxKeys(500);
ListVersionsResult result1;
do {
result1 = obsClient.listVersions(request);
DeleteObjectsRequest deleteRequest = new DeleteObjectsRequest(bucketName);
for(VersionOrDeleteMarker v : result1.getVersions()) {
deleteRequest.addKeyAndVersion(v.getKey(), v.getVersionId());
}
DeleteObjectsResult deleteResult = obsClient.deleteObjects(deleteRequest);
// 获取删除成功的对象
System.out.println(deleteResult.getDeletedObjectResults());
request.setKeyMarker(result1.getNextKeyMarker());
request.setVersionIdMarker(result1.getNextVersionIdMarker());
}while(result.isTruncated());
}
//删除桶
obsClient.deleteBucket(bucketName);
System.out.println("\n------------------\nbucket already delete.");
}
catch (ObsException e)
{
e.printStackTrace();
System.out.println("Response Code: " + e.getResponseCode());
System.out.println("Error Message: " + e.getErrorMessage());
System.out.println("Error Code: " + e.getErrorCode());
System.out.println("Request ID: " + e.getErrorRequestId());
System.out.println("Host ID: " + e.getErrorHostId());
}
finally
{
if (obsClient != null)
{
try
{
obsClient.close();
}
catch (IOException e)
{
}
}
}
}
}
4 附录链接
OBS JAVA SDK使用,官网参考链接:https://support.huaweicloud.com/sdkreference-obs/obs_02_0001.html
- 点赞
- 收藏
- 关注作者
评论(0)