AliyunOASClient和ArchiveManager
AliyunOASClient和ArchiveManager分别是低阶接口、高级接口的入口对象,在每个功能中都会使用到它们,为避免实例程序的冗长,将AliyunOASClient和ArchiveManager的创建在这里单独介绍。
注:在本文档中出现的 aliyunOASClient 均是 AliyunOASClient 实例,archiveManager 均是 ArchiveManager实例
// AccessId和AccessKey配置
ServiceCredentials credentials = new ServiceCredentials(
"[yourAccessId]", "[yourAccessKey]");
// 配置客户端设置
ClientConfiguration clientConf = new ClientConfiguration();
// 指定要连接的服务地址
ServiceHost serviceHost = new ServiceHost("http://cn-hangzhou.oas.aliyuncs.com");
// 用OAS工厂获得AliyunOASClient对象
AliyunOASClient aliyunOASClient = OASFactory.aliyunOASClientFactory(
serviceHost, credentials, clientConf);
// 或者像下面这样,通过ServiceCredentials和url直接创建AliyunOASClient对象
AliyunOASClient aliyunOASClient = OASFactory.aliyunOASClientFactory(
credentials, "http://cn-hangzhou.oas.aliyuncs.com");
// 自定义配置ClientConfiguration
ServiceCredentials credentials = new ServiceCredentials("[yourAccessKeyID]", "[yourAccessKeySecret]");
// 指定要连接的服务地址
ServiceHost serviceHost = new ServiceHost("http://cn-hangzhou.oas.aliyuncs.com");
// 配置客户端设置
ClientConfiguration clientConf = new ClientConfiguration();
ArchiveManager archiveManager = new ArchiveManager(serviceHost, credentials, clientConf);
// 使用默认配置
ServiceCredentials credentials = new ServiceCredentials("[yourAccessKeyID]", "[yourAccessKeySecret]");
ArchiveManager manager = OASFactory.archiveManagerFactory(
credentials, "http://cn-hangzhou.oas.aliyuncs.com");
// 使用AliyunOASClient初始化
AliyunOASClient aliyunOASClient = OASFactory.aliyunOASClientFactory(
credentials, clientConf).withLogger();
ArchiveManager archiveManager = OASFactory.archiveManagerFactory(aliyunOASClient);
// vaultName必须满足已下2个条件:
// 1. 总长度在3~63之间(包括3和63);
// 2. 只允许包含以下字符:
// 0-9(数字),
// a-z(小写英文字母),
// -(短横线),
// _(下划线)
// 其中 短横线 和 下划线 不能作为vaultName的开头和结尾;
String vaultName = "oas_demo";
// 发送创建vault请求
// 创建Vault的名称,用CreateVaultRequest来指定
CreateVaultRequest createRequest = new CreateVaultRequest().
withVaultName(vaultName);
// 发起创建Vault的请求
// 如果有同名的vault存在,OAS会返回已有的vault的vaultId,而不会执行创建动作
try {
CreateVaultResult result = aliyunOASClient.createVault(createRequest);
logger.info("Vault created vaultId={}", result.getVaultId());
logger.info("Vault created vaultLocation={}", result.getLocation());
} catch (OASClientException e) {
logger.error("OASClientException Occured:", e);
} catch (OASServerException e) {
logger.error("OASServerException Occured:", e);
}
// 删除vault是高危动作,因此只能通过vaultId来删除
DeleteVaultRequest deleteVaultRequest = new DeleteVaultRequest().withVaultId(yourVaultId);
try {
OASResult result = aliyunOASClient.deleteVault(deleteVaultRequest);
logger.info("Delete Success! {} {}", result.getRequestId(), result.getDate());
} catch (OASClientException e) {
logger.error("OASClientException Occured:", e);
} catch (OASServerException e) {
logger.error("OASServerException Occured:", e);
}
// java sdk 会帮助用户完成 vaultName 到 vaultId 的转换
// 由此避免了用户对一长串vaultId的记忆负担
String yourVaultName = "oas_demo";
File file = new File("oas_demo_data/random10M.bin");
try {
UploadResult uploadResult = archiveManager.upload(yourVaultName, file);
logger.info("File {} uploaded complete. ArchiveId={},md5={},treeEtag={}",
file.getAbsolutePath(), uploadResult.getArchiveId(),
uploadResult.getHashValue(),
uploadResult.getHashTreeValue());
} catch (OASClientException e) {
logger.error("OASClientException Occured:", e);
} catch (OASServerException e) {
logger.error("OASServerException Occured:", e);
}
File file = new File("oas_demo_data/random120M-2.bin");
//获得uploadId
//文件大小必须大于100MB,否则会抛异常提示用普通上传接口进行上传
String uploadId = archiveManager.initiateMultipartUpload(vaultName, file, "Hello OAS!");
//如果是已有的uploadId,直接使用之前获取过的uploadId
//String uploadId = "[yourUploadId]";
System.out.println("Get uploadId=" + uploadId);
UploadResult uploadResult = archiveManager.uploadWithUploadId(vaultName, file, uploadId);
System.out.println("Archive ID=" + uploadResult.getArchiveId());
String yourVaultName = "oas_demo";
String yourArchiveId = "6086C62DBFFD4A68BAEE9D1B680EC77C8FE6AE617FF47BCD3DB3CB71AFAE29B33431AED14D06D9C4AD251F17C173F3CD";
JobMonitor jobMonitor = archiveManager.downloadAsync(yourVaultName, yourArchiveId);
JobMonitor jobMonitor = archiveManager.downloadInventoryAsync("oas_demo");
archiveManager.downloadJobOutput(yourVaultName, jobId,
new File("oas_demo_data/mySaveFile.bin"));
ServiceCredentials credentials = new ServiceCredentials(
DemoConstants.ACCESS_ID,
DemoConstants.ACCESS_KEY);
// 通过工厂类获得archiveManager接口
ArchiveManager archiveManager = OASFactory.archiveManagerFactory(credentials);
File file = new File("[pathToYourFile]");
final BaseTransfer<UploadResult> bt = archiveManager.uploadAsync(
"[yourVaultName]", file);
//设置最大并发数,默认为3,最大为10
bt.setNumConcurrence(5);
bt.addProgressListener(new ProgressListener() {
@Override
public void onStart(String id) {
// 任务开始时调用,其中id为Multipart Upload任务ID,对于一般上传任务id为空
System.out.println("Start! Upload ID: " + id);
}
@Override
public boolean onError(Range range, Throwable t) {
// 出错时调用,range是出错的字节范围,t是相应的错误
// 当返回true时,BaseTransfer会进行重试,false则放弃
System.out.println("ERROR!!!");
return false;
}
@Override
public void onCompleted() {
// 任务完成时调用
System.out.println("Upload complete");
}
@Override
public void onProgressed(long current, long total) {
// 上传进度,total为文件字节大小,current为当前已上传字节数
System.out.println("Progress: " + current + " / " + total);
}
});
bt.start();
final Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
System.out.println("Running time: " + bt.getRunningTime() + " seconds");
System.out.println("Completed size: " + bt.getSizeCompleted() + " bytes");
System.out.println("Total size: " + bt.getSizeTotal() + " bytes");
System.out.println("Average speed: " + bt.getAverageSpeedInBytesPerSecond()
+ " B/s");
if (bt.isComplete()) {
timer.cancel();
synchronized (bt) {
bt.notify();
}
}
}
}, 0, 1000);
synchronized (bt) {
try {
bt.wait();
} catch (InterruptedException e) {
logger.error("", e);
}
}
// 任务结束
System.out.println("=============================");
System.out.println("Running time: " + bt.getRunningTime() + " seconds");
System.out.println("Completed size: " + bt.getSizeCompleted() + " bytes");
System.out.println("Total size: " + bt.getSizeTotal() + " bytes");
System.out.println("Average speed: " + bt.getAverageSpeedInBytesPerSecond() + " B/s");
UploadResult uploadResult = bt.getResult();
System.out.println("Archive ID: " + uploadResult.getArchiveId());
System.out.println("Hash Value: " + uploadResult.getHashValue());
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。