异步接口与同步接口不同的是方法的返回值,一般来说,返回的对象是[backcolor=transparent]BaseTransfer,用户可通过[backcolor=transparent]ProgressListener监听进度,[backcolor=transparent]SpeedListener监听速度,通过
start开始任务,
stop停止任务,而
waitUntilFinished将会阻塞直至任务完成,
getResult可获取上传或下载结果。具体使用请参考本节的示例。
[backcolor=transparent]ProgressListener、[backcolor=transparent]SpeedListener和[backcolor=transparent]JobStatusListener分别为进度、速度、任务状态,各个的每个接口含义见下文的例子,而[backcolor=transparent]ProgressListenerAdapter、[backcolor=transparent]SpeedListenerAdapter和[backcolor=transparent]JobStatusListenerAdapter分别实现了以上接口,出错时默认会自动重试3次。特别注意的是,部分接口的调用是在IO线程中,在中执行费时的操作将有可能导致网络连接出错甚至中断。
以上传为例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("ContentEtag: " + uploadResult.getContentEtag());
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。