import com.google.api.client.http.HttpResponseException; import com.google.api.services.drive.Drive; import com.google.api.services.drive.model.File; import java.io.IOException; import java.util.Random; // ... public class MyClass { // ... /** * Print a file's metadata with exponential backoff. * * @param service Drive API service instance. * @param fileId ID of the file to print metadata for. * @return The file's metadata. */ static File printFileWithExponentialBackoff(Drive service, String fileId) throws IOException, InterruptedException { Random randomGenerator = new Random(); for (int n = 0; n < 5; ++n) { try { File file = service.files().get(fileId).execute(); System.out.println("Title: " + file.getTitle()); System.out.println("Description: " + file.getDescription()); System.out.println("MIME type: " + file.getMimeType()); return file; } catch (GoogleJsonResponseException e) { if (e.getCode() == 403 && (e.getErrors().get(0).getReason().equals("rateLimitExceeded") || e.getErrors().get(0).getReason().equals("userRateLimitExceeded"))) { // Apply exponential backoff. Thread.sleep((1 << n) * 1000 + randomGenerator.nextInt(1001)); } else { // Other error, re-throw. throw e; } } } System.err.println("There has been an error, the request never succeeded."); return null; } // ... }https://developers.google.com/drive/web/handle-errors#implementing_exponential_backoff
public enum Results { SUCCESS, NOT_READY, THROTTLED, SERVER_ERROR } /* * Performs an asynchronous operation, then polls for the result of the * operation using an incremental delay. */ public static void doOperationAndWaitForResult() { try { // Do some asynchronous operation. long token = asyncOperation(); int retries = 0; boolean retry = false; do { long waitTime = Math.min(getWaitTimeExp(retries), MAX_WAIT_INTERVAL); System.out.print(waitTime + "\n"); // Wait for the result. Thread.sleep(waitTime); // Get the result of the asynchronous operation. Results result = getAsyncOperationResult(token); if (Results.SUCCESS == result) { retry = false; } else if (Results.NOT_READY == result) { retry = true; } else if (Results.THROTTLED == result) { retry = true; } else if (Results.SERVER_ERROR == result) { retry = true; } else { // Some other error occurred, so stop calling the API. retry = false; } } while (retry && (retries++ < MAX_RETRIES)); } catch (Exception ex) { } } /* * Returns the next wait interval, in milliseconds, using an exponential * backoff algorithm. */ public static long getWaitTimeExp(int retryCount) { long waitTime = ((long) Math.pow(2, retryCount) * 100L); return waitTime; }
http://docs.aws.amazon.com/general/latest/gr/api-retries.html
댓글 없음 :
댓글 쓰기