Retry logic with CompletableFuture

后端 未结 7 2161
别跟我提以往
别跟我提以往 2021-01-31 18:26

I need to submit a task in an async framework I\'m working on, but I need to catch for exceptions, and retry the same task multiple times before \"aborting\".

The code I

7条回答
  •  庸人自扰
    2021-01-31 19:06

    Here is an approach that will work for any CompletionStage subclass and does not return a dummy CompletableFuture that does nothing more than wait to get updated by other futures.

    /**
     * Sends a request that may run as many times as necessary.
     *
     * @param request  a supplier initiates an HTTP request
     * @param executor the Executor used to run the request
     * @return the server response
     */
    public CompletionStage asyncRequest(Supplier> request, Executor executor)
    {
        return retry(request, executor, 0);
    }
    
    /**
     * Sends a request that may run as many times as necessary.
     *
     * @param request  a supplier initiates an HTTP request
     * @param executor the Executor used to run the request
     * @param tries    the number of times the operation has been retried
     * @return the server response
     */
    private CompletionStage retry(Supplier> request, Executor executor, int tries)
    {
        if (tries >= MAX_RETRIES)
            throw new CompletionException(new IOException("Request failed after " + MAX_RETRIES + " tries"));
        return request.get().thenComposeAsync(response ->
        {
            if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL)
                return retry(request, executor, tries + 1);
            return CompletableFuture.completedFuture(response);
        }, executor);
    }
    

提交回复
热议问题