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

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

普通上传下载限速

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

#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;

int main(void)
{
    /* 初始化OSS账号信息 */
    std::string AccessKeyId = "yourAccessKeyId";
    std::string AccessKeySecret = "yourAccessKeySecret";
    std::string Endpoint = "yourEndpoint";
    std::string BucketName = "yourBucketName";
    std::string ObjectName = "yourObjectName";

    /* 初始化网络等资源 */
    InitializeSdk();

    ClientConfiguration conf;
    OssClient client(Endpoint, AccessKeyId, AccessKeySecret, conf);

    /* 上传文件 */
    std::shared_ptr<std::iostream> content = std::make_shared<std::fstream>("yourLocalFilename", std::ios::in|std::ios::binary);
    PutObjectRequest putrequest(BucketName, ObjectName,content);
    /* 设置上传流量速度限制为100KB/s */
    getrequest.setTrafficLimit(819200);
    auto putoutcome = client.PutObject(putrequest);

    /* 获取文件到本地内存 */
    GetObjectRequest getrequest(BucketName, ObjectName);
    /* 设置下载流量速度限制为100KB/s */
    getrequest.setTrafficLimit(819200);
    auto getoutcome = client.GetObject(getrequest);

    /* 释放网络等资源 */
    ShutdownSdk();
    return 0;
}

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

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

#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;

int main(void)
{
    /* 初始化OSS账号信息 */
    std::string AccessKeyId = "yourAccessKeyId";
    std::string AccessKeySecret = "yourAccessKeySecret";
    std::string Endpoint = "yourEndpoint";
    std::string BucketName = "yourBucketName";
    std::string PutobjectUrlName = "yourPutobjectUrlName";

    /* 初始化网络等资源 */
    InitializeSdk();

    ClientConfiguration conf;
    OssClient client(Endpoint, AccessKeyId, AccessKeySecret, conf);

    /* 设置签名URL有效时间 */
    std::time_t t = std::time(nullptr) + 1200;
    /* 生成上传文件URL */
    GeneratePresignedUrlRequest putrequest(BucketName, PutobjectUrlName, Http::Put);
    putrequest.setExpires(expires);
    /* 设置上传流量速度限制为100KB/s */
    putrequest.setTrafficLimit(819200);
    auto genOutcome = client.GeneratePresignedUrl(putrequest);

    std::shared_ptr<std::iostream> content = std::make_shared<std::stringstream>();
    *content << "test cpp sdk";

    /* 使用签名URL上传文件 */
    auto outcome = client.PutObjectByUrl(genOutcome.result(), content);

    /* 生成下载文件URL */
    GeneratePresignedUrlRequest getrequest(BucketName, PutobjectUrlName, Http::Get);
    getrequest.setExpires(expires);
    /* 设置下载流量速度限制为100KB/s */
    getrequest.setTrafficLimit(819200);
    genOutcome = client.GeneratePresignedUrl(getrequest);

    /* 使用签名URL下载文件 */
    outcome = client.GetObjectByUrl(genOutcome.result());

    /* 释放网络等资源 */
    ShutdownSdk();
    return 0;
}