La classe OssClient permet de gérer les ressources Object Storage Service (OSS), telles que les buckets et les objets. Avant d'envoyer une requête OSS à l'aide du kit de développement logiciel (SDK) C++, vous devez initialiser une instance OssClient et, si nécessaire, modifier les paramètres par défaut de ClientConfiguration.
Créer une instance OssClient
La classe OssClient est thread-safe, ce qui permet d'utiliser plusieurs threads pour accéder à la même instance. Réutilisez la même instance OssClient ou créez-en plusieurs selon vos besoins.
InitializeSdk() et ShutdownSdk() sont des fonctions globales. Appelez ces fonctions une seule fois au cours du cycle de vie du programme.
(Recommandé) Signature V4
Nous vous recommandons d'utiliser l'algorithme de signature V4, plus sécurisé. Lors de l'initialisation d'une instance avec une signature V4, spécifiez à la fois l'endpoint et l'ID de région Alibaba Cloud pour la requête. Par exemple, un ID de région peut être cn-hangzhou. Déclarez également SignatureVersionType::V4. Les versions 1.10.0 et ultérieures du SDK C++ prennent en charge les signatures V4.
Le code suivant montre comment créer une instance OssClient à l'aide d'un nom de domaine OSS et d'une signature V4. Pour utiliser un nom de domaine personnalisé ou des identifiants Security Token Service (STS), adaptez l'exemple en conséquence.
#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;
}
(Non recommandé) Signature V1
Créer une instance OssClient à l'aide d'un nom de domaine OSS
#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;
}
Créer une instance OssClient à l'aide d'un nom de domaine personnalisé
#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;
}
Créer une instance OssClient à l'aide de STS
Les identifiants d'accès temporaires fournis par Security Token Service (STS) se composent d'une paire AccessKey temporaire (un AccessKey ID et un AccessKey secret) et d'un jeton de sécurité. Pour plus d'informations sur l'obtention d'identifiants d'accès temporaires auprès de STS, consultez Utiliser les identifiants temporaires fournis par STS pour accéder à OSS.
#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;
}
Configurer OssClient
ClientConfiguration est la classe utilisée pour configurer OssClient. Elle permet de définir des paramètres tels que le proxy, le délai de connexion et le nombre maximal de connexions.
Vous pouvez définir les paramètres suivants pour OssClient :
|
Paramètre |
Description |
|
isCname |
Indique s'il faut utiliser un CNAME comme endpoint. Par défaut, cette fonctionnalité n'est pas prise en charge. |
|
userAgent |
L'agent utilisateur, correspondant à l'en-tête User-Agent dans HTTP. La valeur par défaut est aliyun-sdk-cpp/1.X.X. |
|
maxConnections |
La taille du pool de connexions. La valeur par défaut est 16. |
|
requestTimeoutMs |
Le délai d'expiration de la requête en millisecondes. Si aucune donnée n'est reçue dans ce délai, la connexion est fermée. La valeur par défaut est 10 000 ms. |
|
connectTimeoutMs |
Le délai d'expiration pour l'établissement d'une connexion. La valeur par défaut est 5 000 ms. |
|
retryStrategy |
Une politique de nouvelle tentative personnalisée pour les requêtes ayant échoué. |
|
proxyScheme |
Le protocole du proxy. La valeur par défaut est HTTP. |
|
proxyPort |
Le port du serveur proxy. |
|
proxyPassword |
Le mot de passe pour l'authentification auprès du serveur proxy. |
|
proxyUserName |
Le nom d'utilisateur pour l'authentification auprès du serveur proxy. |
|
verifySSL |
Indique s'il faut activer la vérification du certificat SSL. Par défaut, cette fonctionnalité est désactivée. Remarque
Par défaut, la vérification du certificat SSL est activée dans les versions 1.8.2 et ultérieures du SDK C++. |
|
caPath |
Le chemin racine du certificat CA. Ce paramètre prend effet uniquement lorsque verifySSL est défini sur true. Par défaut, ce paramètre est vide. |
|
caFile |
Le chemin du certificat CA. Ce paramètre prend effet uniquement lorsque verifySSL est défini sur true. Par défaut, ce paramètre est vide. |
|
enableCrc64 |
Indique s'il faut activer la vérification CRC64 (contrôle de redondance cyclique 64 bits). Par défaut, cette fonctionnalité est activée. |
|
enableDateSkewAdjustment |
Indique s'il faut activer la correction automatique du décalage temporel des requêtes HTTP. Par défaut, cette fonctionnalité est activée. |
|
sendRateLimiter |
La limite de vitesse d'upload en Ko/s. |
|
recvRateLimiter |
La limite de vitesse de download en Ko/s. |
Définir le délai d'expiration
Le code suivant montre comment définir le délai d'expiration :
#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;
}
Définir la vérification du certificat SSL
Les versions 1.8.2 et ultérieures du SDK C++ activent la vérification du certificat SSL par défaut. Si la vérification du certificat SSL échoue, définissez le chemin correct du certificat ou désactivez la vérification SSL.
Le code suivant montre comment configurer la vérification du certificat SSL :
#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;
}
Définir les limites de débit
Le code suivant montre comment définir des limites de débit pour les uploads ou les downloads :
#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;
}
Définir une politique de nouvelle tentative
Le code suivant définit la politique de nouvelle tentative :
#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;
}
Définir un serveur proxy
Utilisez le code suivant pour configurer un serveur proxy :
#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;
}