Retrying Failed DEW Requests by Using Exponential Backoff
Scenario
If you receive an error message when calling an API, you can use exponential backoff to retry the request.
How It Works
If consecutive errors (such as traffic limiting errors) are reported by the service side, continuous access will keep causing conflicts. Exponential backoff can help you avoid such errors.
Constraints
The current account has an enabled key.
Example
- Prepare basic authentication information.
- ACCESS_KEY: Access key of the Huawei Cloud account. For details, see How Do I Obtain an Access Key (AK/SK)?
- SECRET_ACCESS_KEY: Secret access key of the Huawei Cloud account. For details, see How Do I Obtain an Access Key (AK/SK)?
- PROJECT_ID: site project ID. For details, see Obtaining a Project ID.
- KMS_ENDPOINT: endpoint for accessing KMS.
- Code for exponential backoff:
import com.huaweicloud.sdk.core.auth.BasicCredentials; import com.huaweicloud.sdk.core.auth.ICredential; import com.huaweicloud.sdk.core.exception.ClientRequestException; import com.huaweicloud.sdk.kms.v2.model.EncryptDataRequest; import com.huaweicloud.sdk.kms.v2.model.EncryptDataRequestBody; import com.huaweicloud.sdk.kms.v2.KmsClient; public class KmsEncryptExample { private static final String ACCESS_KEY = "xxxx"; private static final String SECRET_ACCESS_KEY = "xxxx"; private static final String KMS_ENDPOINT = "xxxx"; private static final String KEY_ID = "xxxx"; private static final String PROJECT_ID = "xxxx"; private static KmsClient KmsClientInit() { ICredential auth = new BasicCredentials() .withAk(ACCESS_KEY) .withSk(SECRET_ACCESS_KEY) .withProjectId(PROJECT_ID); return KmsClient.newBuilder() .withCredential(auth) .withEndpoint(KMS_ENDPOINT) .build(); } public static long getWaitTime(int retryCount) { long initialDelay = 200L; return (long) (Math.pow(2, retryCount) * initialDelay); } public static void encryptData(KmsClient client, String plaintext) { EncryptDataRequest request = new EncryptDataRequest().withBody( new EncryptDataRequestBody() .withKeyId(KEY_ID) .withPlainText(plaintext)); client.encryptData(request); } public static void main(String[] args) { int maxRetryTimes = 6; String plaintext = "plaintext"; String errorMsg = "The throttling threshold has been reached"; KmsClient client = KmsClientInit(); for (int i = 0; i < maxRetryTimes; i++) { try { encryptData(client, plaintext); return; } catch (ClientRequestException e) { if (e.getErrorMsg().contains(errorMsg)) { try { Thread.sleep(getWaitTime(i)); } catch (InterruptedException ex) { throw new RuntimeException(ex); } } } } } }
Feedback
Was this page helpful?
Provide feedbackThank you very much for your feedback. We will continue working to improve the documentation.