本文介绍如何在上传、下载文件时,通过在请求中携带x-oss-traffic-limit参数并设置限速值,以保证其他应用的正常带宽。

说明 有关单链接限速的使用场景及注意事项的更多信息,请参考开发指南的 单链接限速文档。

普通上传下载限速

以下代码用于普通上传、下载文件时设置单链接限速:

// Endpoint以杭州为例,其它Region请按实际情况填写。
String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
// 阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维,请登录 https://ram.console.aliyun.com 创建RAM账号。
String accessKeyId = "<yourAccessKeyId>";
String accessKeySecret = "<yourAccessKeySecret>";

String bucketName = "<yourBucketName>"
String objectName = "<yourObjectName>"
String localFileName = "<yourLocalFileName>"
String downLoadFileName = "<yourDownLoadFileName>"

// 限速100KB/s,即819200bit/s。
int limitSpeed = 100 * 1024 * 8;

// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

// 限速上传。
InputStream inputStream = new FileInputStream(localFileName);
PutObjectRequest PutObjectRequest = new PutObjectRequest(bucketName, key, inputStream);
PutObjectRequest.setTrafficLimit(limitSpeed);
ossClient.putObject(PutObjectRequest);

// 限速下载。
GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, key);
getObjectRequest.setTrafficLimit(limitSpeed);
File localFile = new File(downLoadFileName);
ossClient.getObject(getObjectRequest, localFile);

 ossClient.shutdown();

使用签名URL方式上传下载限速

以下代码用于使用签名URL方式上传、下载文件时设置单链接限速:

// Endpoint以杭州为例,其它Region请按实际情况填写。
String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
// 阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维,请登录 https://ram.console.aliyun.com 创建RAM账号。
String accessKeyId = "<yourAccessKeyId>";
String accessKeySecret = "<yourAccessKeySecret>";

String bucketName = "<yourBucketName>";
String objectName = "<yourObjectName>";
String localFileName = "<yourLocalFileName>";
String downLoadFileName = "<yourDownLoadFileName>";

// 限速100KB/s,即819200bit/s。
int limitSpeed = 100 * 1024 * 8;

// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

// 创建限速上传的url, 有效期60s。
Date date = new Date(); 
date.setTime(date.getTime() + 60 * 1000);
GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, objectName, HttpMethod.PUT);
request.setExpiration(date);
request.setTrafficLimit(limitSpeed);
URL signedUrl = ossClient.generatePresignedUrl(request);
System.out.println("put object url" = signedUrl);

// 限速上传。
InputStream inputStream = new FileInputStream(localFileName);
ossClient.putObject(signedUrl, instream, -1, null, true);

// 创建限速下载的url, 有效期60s。
date = new Date(); 
date.setTime(date.getTime() + 60 * 1000);
request = new GeneratePresignedUrlRequest(bucketName, key, HttpMethod.GET);
request.setExpiration(date);
request.setTrafficLimit(limitSpeed);
signedUrl = ossClient.generatePresignedUrl(request);
System.out.println("get object url" = signedUrl);

// 限速下载。
GetObjectRequest getObjectRequest =  new GetObjectRequest(signedUrl, null);
ossClient.getObject(getObjectRequest, downLoadFileName);

ossClient.shutdown();