OssClient sınıfı, paketler ve nesneler gibi Object Storage Service (OSS) kaynaklarını yönetmek için kullanılır. C++ yazılım geliştirme kiti (SDK) kullanarak bir OSS isteği göndermeden önce bir OssClient örneğini başlatmanız ve gerekirse varsayılan ClientConfiguration ayarlarını değiştirmeniz gerekir.
OssClient örneği oluşturun
OssClient sınıfı iş parçacığı güvenlidir; bu sayede aynı örneğe erişmek için birden fazla iş parçacığı kullanabilirsiniz. Gereksinimlerinize bağlı olarak aynı OssClient örneğini yeniden kullanabilir veya birden fazla örnek oluşturabilirsiniz.
InitializeSdk() ve ShutdownSdk() genel işlevlerdir. Bu işlevleri programın yaşam döngüsü boyunca yalnızca bir kez çağırmanız gerekir.
(Önerilen) V4 imzası
Daha güvenli olan V4 imza algoritmasını kullanmanızı öneririz. Bir örneği V4 imzasıyla başlattığınızda istek için hem uç noktayı hem de Alibaba Cloud bölge kimliğini belirtmeniz gerekir. Örneğin, bir bölge kimliği cn-hangzhou olabilir. Ayrıca SignatureVersionType::V4 değerini bildirmeniz gerekir. C++ SDK'nın 1.10.0 ve sonraki sürümleri V4 imzalarını destekler.
Aşağıdaki kod, bir OSS alan adı ve V4 imzası kullanarak OssClient örneğinin nasıl oluşturulacağını gösterir. Özel bir alan adı veya Security Token Service (STS) kimlik bilgisi kullanmak için örneği buna göre değiştirin.
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;
int main(void)
{
/* Initialize the OSS account information. */
/* Set yourEndpoint to the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
std::string Endpoint = "yourEndpoint";
/* Set yourRegion to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. */
std::string Region = "yourRegion";
/* Initialize resources, such as network resources. */
InitializeSdk();
ClientConfiguration conf;
conf.signatureVersion = SignatureVersionType::V4;
/* Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. */
auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
OssClient client(Endpoint, credentialsProvider, conf);
client.SetRegion(Region);
/* Release resources, such as network resources. */
ShutdownSdk();
return 0;
}
(Önerilmez) V1 imzası
Alibaba Cloud Object Storage Service (OSS), 1 Mart 2025 tarihinden itibaren yeni kullanıcılar (yani yeni UID'ler) için V1 imzasını sunmamaktadır. OSS, 1 Eylül 2025 tarihinden itibaren V1 imzasını güncellemeyi ve bakımını durduracak ve yeni nesne depolama paketleri için V1 imzasını sunmayacaktır. Hizmet kesintilerini önlemek için en kısa sürede V4 imzasına geçiş yapın. Daha fazla bilgi için bkz. Duyuru.
Bir OSS alan adı kullanarak OssClient örneği oluşturma
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;
int main(void)
{
/* Initialize the OSS account information. */
/* Set yourEndpoint to the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
std::string Endpoint = "yourEndpoint";
/* Initialize resources, such as network resources. */
InitializeSdk();
ClientConfiguration conf;
/* Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. */
auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
OssClient client(Endpoint, credentialsProvider, conf);
/* Release resources, such as network resources. */
ShutdownSdk();
return 0;
}
Özel bir alan adı kullanarak OssClient örneği oluşturma
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;
int main(void)
{
/* Initialize the OSS account information. */
/* Set yourEndpoint to the custom domain name. */
std::string Endpoint = "yourEndpoint";
/* Initialize resources, such as network resources. */
InitializeSdk();
ClientConfiguration conf;
conf.isCname = true;
/* Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. */
auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
OssClient client(Endpoint, credentialsProvider, conf);
/* Release resources, such as network resources. */
ShutdownSdk();
return 0;
}
STS kullanarak OssClient örneği oluşturma
Security Token Service (STS) tarafından sağlanan geçici erişim kimlik bilgileri; geçici bir AccessKey çiftinden (bir AccessKey ID ve bir AccessKey secret) ve bir güvenlik belirtecinden oluşur. STS'den geçici erişim kimlik bilgilerinin nasıl alınacağı hakkında daha fazla bilgi için bkz. OSS'e erişmek için STS tarafından sağlanan geçici kimlik bilgilerini kullanma.
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;
int main(void)
{
/* Set yourEndpoint to the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
std::string Endpoint = "yourEndpoint";
/* Initialize resources, such as network resources. */
InitializeSdk();
ClientConfiguration conf;
/* Obtain access credentials from environment variables. Before you run this code, make sure that the temporary AccessKey pair and security token are set as environment variables. */
auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
OssClient client(Endpoint, credentialsProvider, conf);
/* Release resources, such as network resources. */
ShutdownSdk();
return 0;
}
OssClient'ı yapılandırın
ClientConfiguration, OssClient'ı yapılandırmak için kullanılan sınıftır. Bu sınıfı proxy, bağlantı zaman aşımı ve maksimum bağlantı sayısı gibi parametreleri ayarlamak için kullanabilirsiniz.
OssClient için aşağıdaki parametreleri ayarlayabilirsiniz:
|
Parametre |
Açıklama |
|
isCname |
Uç nokta olarak CNAME kullanılıp kullanılmayacağını belirtir. Varsayılan olarak bu özellik desteklenmez. |
|
userAgent |
HTTP'deki User-Agent üst bilgisi olan kullanıcı aracısı. Varsayılan değer aliyun-sdk-cpp/1.X.X'tir. |
|
maxConnections |
Bağlantı havuzunun boyutu. Varsayılan değer 16'dır. |
|
requestTimeoutMs |
Milisaniye cinsinden istek zaman aşımı süresi. Zaman aşımı süresi içinde veri alınmazsa bağlantı kapatılır. Varsayılan değer 10.000 ms'dir. |
|
connectTimeoutMs |
Bağlantı kurma zaman aşımı süresi. Varsayılan değer 5.000 ms'dir. |
|
retryStrategy |
Başarısız istekler için özel bir yeniden deneme ilkesi. |
|
proxyScheme |
Proxy protokolü. Varsayılan değer HTTP'dir. |
|
proxyPort |
Proxy sunucusunun bağlantı noktası. |
|
proxyPassword |
Proxy sunucusu kimlik doğrulaması için parola. |
|
proxyUserName |
Proxy sunucusu kimlik doğrulaması için kullanıcı adı. |
|
verifySSL |
SSL sertifika doğrulamasının etkinleştirilip etkinleştirilmeyeceğini belirtir. Varsayılan olarak bu özellik devre dışı bırakılır. Not
Varsayılan olarak, SSL sertifika doğrulaması C++ SDK 1.8.2 ve sonraki sürümlerde etkindir. |
|
caPath |
CA sertifikasının kök yolu. Bu parametre yalnızca verifySSL true olarak ayarlandığında etkili olur. Varsayılan olarak bu parametre boştur. |
|
caFile |
CA sertifikasının yolu. Bu parametre yalnızca verifySSL true olarak ayarlandığında etkili olur. Varsayılan olarak bu parametre boştur. |
|
enableCrc64 |
64 bit döngüsel yedeklilik denetimi (CRC64) doğrulamasının etkinleştirilip etkinleştirilmeyeceğini belirtir. Varsayılan olarak bu özellik etkindir. |
|
enableDateSkewAdjustment |
HTTP istek zamanı sapması için otomatik düzeltmenin etkinleştirilip etkinleştirilmeyeceğini belirtir. Varsayılan olarak bu özellik etkindir. |
|
sendRateLimiter |
KB/sn cinsinden yükleme hızı sınırı. |
|
recvRateLimiter |
KB/sn cinsinden indirme hızı sınırı. |
Zaman aşımı süresini ayarlayın
Aşağıdaki kod, zaman aşımı süresinin nasıl ayarlanacağını gösterir:
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;
int main(void)
{
/* Initialize the OSS account information. */
/* Set yourEndpoint to the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
std::string Endpoint = "yourEndpoint";
/* Set yourRegion to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. */
std::string Region = "yourRegion";
/* Initialize resources, such as network resources. */
InitializeSdk();
ClientConfiguration conf;
conf.signatureVersion = SignatureVersionType::V4;
/* Set the size of the connection pool. The default value is 16. */
conf.maxConnections = 20;
/* Set the request timeout period. If no data is received within this period, the connection is closed. The default value is 10,000 ms. */
conf.requestTimeoutMs = 8000;
/* Set the timeout period for establishing a connection. The default value is 5,000 ms. */
conf.connectTimeoutMs = 8000;
/* Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. */
auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
OssClient client(Endpoint, credentialsProvider, conf);
client.SetRegion(Region);
/* Release resources, such as network resources. */
ShutdownSdk();
return 0;
}
SSL sertifika doğrulamasını ayarlayın
C++ SDK 1.8.2 ve sonraki sürümler varsayılan olarak SSL sertifika doğrulamasını etkinleştirir. SSL sertifika doğrulaması başarısız olursa doğru sertifika yolunu ayarlayabilir veya SSL sertifika doğrulamasını devre dışı bırakabilirsiniz.
Aşağıdaki kod, SSL sertifika doğrulamasının nasıl ayarlanacağını gösterir:
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;
int main(void)
{
/* Initialize the OSS account information. */
/* Set yourEndpoint to the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
std::string Endpoint = "yourEndpoint";
/* Set yourRegion to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. */
std::string Region = "yourRegion";
/* Initialize resources, such as network resources. */
InitializeSdk();
ClientConfiguration conf;
conf.signatureVersion = SignatureVersionType::V4;
/* Set the switch for SSL certificate verification. The default value is true, which enables verification. */
conf.verifySSL = true;
/* Set the root path of the CA certificate. This parameter takes effect only when verifySSL is set to true. By default, this parameter is empty. */
conf.caPath = "/etc/ssl/certs/";
/* Set the path of the CA certificate. This parameter takes effect only when verifySSL is set to true. By default, this parameter is empty. */
conf.caFile = "/etc/ssl/certs/ca-certificates.crt";;
/* Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. */
auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
OssClient client(Endpoint, credentialsProvider, conf);
client.SetRegion(Region);
/* Release resources, such as network resources. */
ShutdownSdk();
return 0;
}
Hız sınırlarını ayarlayın
Aşağıdaki kod, yüklemeler veya indirmeler için hız sınırlarının nasıl ayarlanacağını gösterir:
#include <alibabacloud/oss/OssClient.h>
#include <alibabacloud/oss/client/RateLimiter.h>
using namespace AlibabaCloud::OSS;
class UserRateLimiter : public RateLimiter
{
public:
UserRateLimiter() : rate_(0) {};
~UserRateLimiter() {};
virtual void setRate(int rate) { rate_ = rate; };
virtual int Rate() const { return rate_; };
private:
int rate_;
};
int main(void)
{
/* Initialize the OSS account information. */
/* Set yourEndpoint to the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
std::string Endpoint = "yourEndpoint";
/* Set yourRegion to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. */
std::string Region = "yourRegion";
/* Enter the bucket name. Example: examplebucket. */
std::string BucketName = "examplebucket";
/* Enter the full path of the object. The path cannot include the bucket name. Example: exampledir/exampleobject.txt. */
std::string ObjectName = "exampledir/exampleobject.txt";
/* Initialize resources, such as network resources. */
InitializeSdk();
ClientConfiguration conf;
conf.signatureVersion = SignatureVersionType::V4;
auto sendrateLimiter = std::make_shared<UserRateLimiter>();
auto recvrateLimiter = std::make_shared<UserRateLimiter>();
conf.sendRateLimiter = sendrateLimiter;
conf.recvRateLimiter = recvrateLimiter;
/* Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. */
auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
OssClient client(Endpoint, credentialsProvider, conf);
client.SetRegion(Region);
/* Set the download rate limit in KB/s. */
recvrateLimiter->setRate(256);
/* Set the upload rate limit in KB/s. */
sendrateLimiter->setRate(256);
/* Upload a file. Set yourLocalFilename to the full path of the local file. */
auto outcome = client.PutObject(BucketName, ObjectName, "yourLocalFilename");
/* Update the upload rate limit in KB/s during the upload. */
sendrateLimiter->setRate(300);
/* Release resources, such as network resources. */
ShutdownSdk();
return 0;
}
Yeniden deneme ilkesi ayarlayın
Aşağıdaki kod yeniden deneme ilkesini ayarlar:
#include <alibabacloud/oss/OssClient.h>
#include <alibabacloud/oss/client/RetryStrategy.h>
using namespace AlibabaCloud::OSS;
class UserRetryStrategy : public RetryStrategy
{
public:
/* maxRetries specifies the maximum number of retries. scaleFactor is the scaling factor for the retry interval. */
UserRetryStrategy(long maxRetries = 3, long scaleFactor = 300) :
m_scaleFactor(scaleFactor), m_maxRetries(maxRetries)
{}
/* You can customize the shouldRetry function to determine whether to retry a request. */
bool shouldRetry(const Error & error, long attemptedRetries) const;
/* You can customize the calcDelayTimeMs function to calculate the delay before a retry. */
long calcDelayTimeMs(const Error & error, long attemptedRetries) const;
private:
long m_scaleFactor;
long m_maxRetries;
};
bool UserRetryStrategy::shouldRetry(const Error & error, long attemptedRetries) const
{
if (attemptedRetries >= m_maxRetries)
return false;
long responseCode = error.Status();
//http code
if ((responseCode == 403 && error.Message().find("RequestTimeTooSkewed") != std::string::npos) ||
(responseCode > 499 && responseCode < 599)) {
return true;
}
else {
switch (responseCode)
{
//curl error code
case (ERROR_CURL_BASE + 7): //CURLE_COULDNT_CONNECT
case (ERROR_CURL_BASE + 18): //CURLE_PARTIAL_FILE
case (ERROR_CURL_BASE + 23): //CURLE_WRITE_ERROR
case (ERROR_CURL_BASE + 28): //CURLE_OPERATION_TIMEDOUT
case (ERROR_CURL_BASE + 52): //CURLE_GOT_NOTHING
case (ERROR_CURL_BASE + 55): //CURLE_SEND_ERROR
case (ERROR_CURL_BASE + 56): //CURLE_RECV_ERROR
case (ERROR_CURL_BASE + 65): //CURLE_SEND_FAIL_REWIND
return true;
default:
break;
};
}
return false;
}
long UserRetryStrategy::calcDelayTimeMs(const Error & error, long attemptedRetries) const
{
return (1 << attemptedRetries) * m_scaleFactor;
}
int main(void)
{
/* Initialize the OSS account information. */
/* Set yourEndpoint to the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
std::string Endpoint = "yourEndpoint";
/* Set yourRegion to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. */
std::string Region = "yourRegion";
/* Initialize resources, such as network resources. */
InitializeSdk();
ClientConfiguration conf;
conf.signatureVersion = SignatureVersionType::V4;
/* Set the number of retries for failed requests. The default value is 3. */
auto defaultRetryStrategy = std::make_shared<UserRetryStrategy>(5);
conf.retryStrategy = defaultRetryStrategy;
/* Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. */
auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
OssClient client(Endpoint, credentialsProvider, conf);
client.SetRegion(Region);
/* Release resources, such as network resources. */
ShutdownSdk();
return 0;
}
Bir proxy sunucusu ayarlayın
Bir proxy sunucusu ayarlamak için aşağıdaki kodu kullanın:
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;
int main(void)
{
/* Initialize the OSS account information. */
/* Set yourEndpoint to the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
std::string Endpoint = "yourEndpoint";
/* Set yourRegion to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. */
std::string Region = "yourRegion";
/* Initialize resources, such as network resources. */
InitializeSdk();
ClientConfiguration conf;
conf.signatureVersion = SignatureVersionType::V4;
/* Set the address of the proxy server. */
conf.proxyHost = "yourProxyHost";
/* Set the port of the proxy server. */
conf.proxyPort = 1234;
/* Optional. Set the username for proxy server authentication. */
conf.proxyUserName = "yourProxyUserName";
/* Optional. Set the password for proxy server authentication. */
conf.proxyPassword = "yourProxyPassword";
/* Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. */
auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
OssClient client(Endpoint, credentialsProvider, conf);
client.SetRegion(Region);
/* Release resources, such as network resources. */
ShutdownSdk();
return 0;
}