Tencent Cloud Java SDK 3.0

repository·master·Indexed 20 days ago

https://github.com/tencentcloud/tencentcloud-sdk-java

A collection of tools for Java developers to integrate and debug Tencent Cloud product APIs. It provides structured classes for requests, responses, and clients for various cloud services. The SDK supports JDK 7 or higher and offers both product-specific and full SDK installations via Maven. Key features include customizable HTTP and Client profiles, internationalization support, debug logging, regional disaster recovery (circuit breaker), request retries, and a Common Client for generic API calls.

Tokens
9.5K
Snippets
23
Records
31
Agent score
68%

What's inside tencentcloud-sdk-java

  1. Configure Regional Disaster Recovery (Circuit Breaker)

    master

    Since version 3.1.779, the SDK supports regional disaster recovery. By default, if a request fails $\ge 5$ times and the failure rate is $\ge 75%$, the SDK automatically switches to a backup region.

    You can customize this behavior by setting a backupEndpoint and defining a custom CircuitBreaker with specific maxFailNum and maxFailPercentage settings. Note: This feature only supports synchronous requests for a single client.

    // Set the backup endpoint (do not include the service name, e.g., 'cvm')
    clientProfile.setBackupEndpoint("ap-guangzhou.tencentcloudapi.com");
    
    // Customize circuit breaker conditions
    CircuitBreaker.Setting setting = new CircuitBreaker.Setting();
    setting.maxFailNum = 6;
    setting.maxFailPercentage = 0.8f;
    CircuitBreaker rb = new CircuitBreaker(setting);
    client.setRegionBreaker(rb);
  2. Use the Common Client for generic API calls

    master

    Starting from version 3.1.303, the SDK supports a Common Client approach. This allows you to make calls to any product by only installing the Common package, without needing the specific product SDK.

    Requirements/Limitations:

    • You must know the exact parameters required by the interface.
    • It currently only supports POST requests.
    • The signature method must be version 3.
  3. Manage credentials for Tencent Cloud SDK

    master

    The Java SDK supports several methods for credential management to authenticate your requests. You can use specific providers or a default provider chain.

    1. Environment Variables

    Reads TENCENTCLOUD_SECRET_ID and TENCENTCLOUD_SECRET_KEY from your environment.

    2. Configuration Files

    Uses a .ini file at the following locations:

    • Windows: c:\Users\NAME\.tencentcloud\credentials
    • Linux: ~/.tencentcloud/credentials or /etc/tencentcloud/credentials

    Format:

    [default]
    secret_id = xxxxx
    secret_key = xxxxx

    3. Role Assumption (STS)

    Use temporary credentials by providing a roleArn and session name. The SDK automatically refreshes these credentials.

    4. Instance Roles (CVM)

    When running on a CVM instance with an attached role, the SDK can automatically fetch and refresh temporary credentials via the instance metadata service.

    5. TKE OIDC Credentials

    Used for Pod-based authentication in Tencent Kubernetes Engine (TKE).

    6. Default Credentials Provider Chain

    To simplify management, use DefaultCredentialsProvider. It attempts to retrieve credentials in the following order: Environment Variables $\rightarrow$ Configuration Files $\rightarrow$ Instance Roles $\rightarrow$ TKE OIDC Credentials. It returns the first successful match.

    // 1. Environment Variables
    Credential cred = new EnvironmentVariableCredentialsProvider().getCredentials();
    
    // 2. Configuration Files
    Credential cred = new ProfileCredentialsProvider().getCredentials();
    
    // 3. Role Assumption
    Credential cred = new STSCredential("secretId", "secretKey", "roleArn", "roleSessionName");
    
    // 4. Instance Roles
    Credential cred = new CvmRoleCredential();
    
    // 5. TKE OIDC
    OIDCRoleArnProvider provider = new OIDCRoleArnProvider();
    Credential credential = provider.getCredentials();
    
    // 6. Default Provider Chain
    Credential cred = new DefaultCredentialsProvider().getCredentials();
  4. Install a specific product SDK via Maven

    master

    To minimize project size, it is recommended to install only the SDK for the specific product you need. Use the following Maven dependency format, replacing 指定产品包名 with the appropriate product artifact ID (e.g., tencentcloud-sdk-java-cvm for CVM).

    Check the products.md file for the correct package name abbreviations.

    <dependency>
        <groupId>com.tencentcloudapi</groupId>
        <artifactId>tencentcloud-sdk-java-cvm</artifactId>
        <version>3.1.1000</version>
    </dependency>
  5. Implement a detailed API call workflow

    master

    To call a Tencent Cloud API using the detailed pattern, follow these steps:

    1. Import necessary classes: Import Credential, TencentCloudSDKException, the specific product Client, its Request and Response models, and configuration profiles (ClientProfile, HttpProfile).
    2. Authenticate: Instantiate a Credential object using your secretId and secretKey. It is recommended to use environment variables for security.
    3. Configure HTTP settings: Use HttpProfile to set parameters like protocol (e.g., https://), reqMethod (e.g., GET), connTimeout, writeTimeout, readTimeout, and endpoint.
    4. Configure Client settings: Use ClientProfile to set the signMethod (default is TC3-HMAC-SHA256), httpProfile, debug mode, and language (ZH_CN or EN_US).
    5. Initialize the Client: Create the product-specific client (e.g., CvmClient) by passing the Credential, the target region, and the ClientProfile.
    6. Prepare the Request: Instantiate the specific Request object for the API and populate its fields (e.g., using Filter objects for querying).
    7. Execute the Call: Call the method on the client object corresponding to the request. This returns a Response object.
    8. Handle Results and Errors: Use Response.toJsonString(resp) to output JSON or access individual fields. Wrap the call in a try-catch block to handle TencentCloudSDKException.
    import com.tencentcloudapi.common.Credential;
    import com.tencentcloudapi.common.exception.TencentCloudSDKException;
    import com.tencentcloudapi.cvm.v20170312.CvmClient;
    import com.tencentcloudapi.cvm.v20170312.models.DescribeInstancesRequest;
    import com.tencentcloudapi.cvm.v20170312.models.DescribeInstancesResponse;
    import com.tencentcloudapi.cvm.v20170312.models.Filter;
    import com.tencentcloudapi.common.profile.ClientProfile;
    import com.tencentcloudapi.common.profile.HttpProfile;
    import com.tencentcloudapi.common.profile.Language;
    
    public class Example {
        public static void main(String[] args) {
            try {
                Credential cred = new Credential(System.getenv("TENCENTCLOUD_SECRET_ID"), System.getenv("TENCENTCLOUD_SECRET_KEY"));
                
                HttpProfile httpProfile = new HttpProfile();
                httpProfile.setProtocol("https://");
                httpProfile.setEndpoint("cvm.ap-shanghai.tencentcloudapi.com");
    
                ClientProfile clientProfile = new ClientProfile();
                clientProfile.setHttpProfile(httpProfile);
                clientProfile.setDebug(true);
                clientProfile.setLanguage(Language.EN_US);
    
                CvmClient client = new CvmClient(cred, "ap-shanghai", clientProfile);
    
                DescribeInstancesRequest req = new DescribeInstancesRequest();
                Filter respFilter = new Filter();
                respFilter.setName("zone");
                respFilter.setValues(new String[] { "ap-shanghai-1", "ap-shanghai-2" });
                req.setFilters(new Filter[] { respFilter });
    
                DescribeInstancesResponse resp = client.DescribeInstances(req);
                System.out.println(DescribeInstancesResponse.toJsonString(resp));
                System.out.println(resp.getTotalCount());
            } catch (TencentCloudSDKException e) {
                System.out.println(e.toString());
            }
        }
    }
  6. Enable SDK Debug Logging

    master

    Since version 3.1.80, you can enable debug mode in ClientProfile to print SDK exception information and traffic details. The SDK uses commons-logging for logging. To use a specific logger like log4j, you must add the log4j dependency to your pom.xml and set the org.apache.commons.logging.Log system property.

    // Enable debug mode
    ClientProfile clientProfile = new ClientProfile();
    clientProfile.setDebug(true);
    
    // Configure Log4j via system property
    System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.Log4JLogger");
  7. Configure Language support

    master

    Since version 3.1.16, the SDK supports the Language parameter to handle internationalization. The default behavior is determined by the specific product API (usually Chinese), but you can explicitly set it to ZH_CN (Chinese) or EN_US (English) via ClientProfile.

    import com.tencentcloudapi.common.profile.ClientProfile;
    import com.tencentcloudapi.common.profile.Language;
    
    ClientProfile clientProfile = new ClientProfile();
    clientProfile.setLanguage(Language.ZH_CN);
  8. Configure Maven mirror for faster downloads

    master

    If you cannot access the official Maven repository directly, you can use the Tencent Maven mirror by adding the following configuration to your settings.xml file in the <mirrors> section.

    <mirror>
      <id>tencent</id>
      <name>tencent maven mirror</name>
      <url>https://mirrors.tencent.com/nexus/repository/maven-public/</url>
      <mirrorOf>*</mirrorOf>
    </mirror>