La clase OssClient se usa para gestionar los recursos de Object Storage Service (OSS), como los buckets y los objetos. Antes de enviar una solicitud a OSS con el kit de desarrollo de software (SDK) de C++, debe inicializar una instancia de OssClient y, si es necesario, modificar la configuración predeterminada de ClientConfiguration.
Crear una instancia de OssClient
La clase OssClient es segura para hilos, lo que le permite usar varios hilos para acceder a la misma instancia. Reutilice la misma instancia de OssClient o cree varias instancias según sus necesidades.
InitializeSdk() y ShutdownSdk() son funciones globales. Llámelas solo una vez durante el ciclo de vida del programa.
(Recomendado) Firma V4
Se recomienda usar el algoritmo de firma V4, ya que es más seguro. Cuando inicialice una instancia con una firma V4, especifique tanto el endpoint como el identificador de región de Alibaba Cloud para la solicitud. Por ejemplo, un identificador de región puede ser cn-hangzhou. También debe declarar SignatureVersionType::V4. Las versiones 1.10.0 y posteriores del SDK de C++ admiten firmas V4.
A continuación se muestra un ejemplo de cómo crear una instancia de OssClient mediante un nombre de dominio de OSS y una firma V4. Si necesita usar un nombre de dominio personalizado o credenciales de Security Token Service (STS), modifique el ejemplo según corresponda.
#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;
}
(No recomendado) Firma V1
A partir del 1 de marzo de 2025, Alibaba Cloud Object Storage Service (OSS) dejó de ofrecer la firma V1 a los nuevos usuarios (es decir, a los nuevos UID). Desde el 1 de septiembre de 2025, OSS dejará de actualizar y mantener la firma V1, y ya no estará available para los nuevos buckets de object storage. Cambie a la firma V4 lo antes posible para evitar interrupciones en el servicio. Para obtener más información, consulte Anuncio.
Crear una instancia de OssClient con un nombre de dominio de 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;
}
Crear una instancia de OssClient con un nombre de dominio personalizado
#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;
}
Crear una instancia de OssClient con STS
Las credenciales de acceso temporal que proporciona Security Token Service (STS) constan de un par de AccessKey temporal (un AccessKey ID y un AccessKey secret) y un token de seguridad. Para obtener más información sobre cómo conseguir credenciales de acceso temporal desde STS, consulte Use temporary credentials provided by STS to access 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;
}
Configurar OssClient
ClientConfiguration es la clase que se usa para configurar OssClient. Con ella puede establecer parámetros como el proxy, el tiempo de espera de conexión y el número máximo de conexiones.
Puede configurar los siguientes parámetros para OssClient:
|
Parámetro |
Descripción |
|
isCname |
Indica si se usa un CNAME como endpoint. De forma predeterminada, esta función no es compatible. |
|
userAgent |
El agente de usuario, que corresponde al encabezado User-Agent en HTTP. El valor predeterminado es aliyun-sdk-cpp/1.X.X. |
|
maxConnections |
El tamaño del pool de conexiones. El valor predeterminado es 16. |
|
requestTimeoutMs |
El tiempo de espera de la solicitud en milisegundos. Si no se reciben datos dentro de este periodo, la conexión se cierra. El valor predeterminado es 10 000 ms. |
|
connectTimeoutMs |
El tiempo de espera para establecer una conexión. El valor predeterminado es 5000 ms. |
|
retryStrategy |
Una política de reintento personalizada para las solicitudes con errores. |
|
proxyScheme |
El protocolo del proxy. El valor predeterminado es HTTP. |
|
proxyPort |
El puerto del servidor proxy. |
|
proxyPassword |
La contraseña para la autenticación del servidor proxy. |
|
proxyUserName |
El nombre de usuario para la autenticación del servidor proxy. |
|
verifySSL |
Indica si se habilita la verificación del certificado SSL. De forma predeterminada, esta función está deshabilitada. Nota
En el SDK de C++ versión 1.8.2 y posteriores, la verificación del certificado SSL se habilita de forma predeterminada. |
|
caPath |
La ruta raíz del certificado de CA. Este parámetro solo surte efecto cuando verifySSL se establece en true. De forma predeterminada, este parámetro está vacío. |
|
caFile |
La ruta del certificado de CA. Este parámetro solo surte efecto cuando verifySSL se establece en true. De forma predeterminada, este parámetro está vacío. |
|
enableCrc64 |
Indica si se habilita la verificación de redundancia cíclica de 64 bits (CRC64). De forma predeterminada, esta función está habilitada. |
|
enableDateSkewAdjustment |
Indica si se habilita la corrección automática de la desviación horaria en las solicitudes HTTP. De forma predeterminada, esta función está habilitada. |
|
sendRateLimiter |
El límite de velocidad de carga en KB/s. |
|
recvRateLimiter |
El límite de velocidad de descarga en KB/s. |
Establecer el tiempo de espera
A continuación se muestra un ejemplo de cómo establecer el tiempo de espera:
#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;
}
Configurar la verificación del certificado SSL
El SDK de C++ versión 1.8.2 y posteriores habilita la verificación del certificado SSL de forma predeterminada. Si esta verificación falla, establezca la ruta correcta del certificado o deshabilítela.
A continuación se muestra cómo configurar la verificación del certificado 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;
}
Establecer límites de velocidad
A continuación se muestra cómo establecer límites de velocidad para las cargas o descargas:
#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;
}
Establecer una política de reintento
El siguiente código establece la política de reintento:
#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;
}
Configurar un servidor proxy
Use el siguiente código para configurar un servidor 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;
}