rishi
rishi

Reputation: 31

How to write java client code for retry call to Java webservice

I have to write a Java client code for a webservice published by some other party. In that client code I have to give option for retry for specified number of times if any timeout occurs.

In webservice call I have passed non persisten objects, so in retry process I think these objects should be saved.

A code sample would be very helpful.

Upvotes: 3

Views: 5138

Answers (2)

yegor256
yegor256

Reputation: 105083

AOP and Java annotations is the right way to do it. I would recommend a read-made mechanism from jcabi-aspects (I'm a developer):

import com.jcabi.aspects.RetryOnFailure;
@RetryOnFailure(attempts = 4)
public String load(URL url) {
  // sensitive operation that may throw an exception
  return url.openConnection().getContent();
}

Upvotes: 5

Vikdor
Vikdor

Reputation: 24134

This should help you get started (definitely not production quality though). The actual webservice call should be in a class that implements Callable<T> where T is the type of response expected from the webservice.

import java.util.List;
import java.util.concurrent.Callable;

public class RetryHelper<T>
{
    // Number of times to retry before giving up.
    private int numTries;

    // Delay between retries.
    private long delay;

    // The actual callable that call the webservice and returns the response object.
    private Callable<T> callable;

    // List of exceptions expected that should result in a null response 
    // being returned.
    private List<Class<? extends Exception>> allowedExceptions;

    public RetryHelper(
        int numTries,
        long delay,
        Callable<T> callable,
        List<Class<? extends Exception>> allowedExceptions)
    {
        this.numTries = numTries;
        this.delay = delay;
        this.callable = callable;
        this.allowedExceptions = allowedExceptions;
    }

    public T run()
    {
        int count = 0;
        while (count < numTries)
        {
            try
            {
                return callable.call();
            }
            catch (Exception e)
            {
                if (allowedExceptions.contains(e.getClass()))
                {
                    return null;
                }
            }
            count++;
            try
            {
                Thread.sleep(delay);
            }
            catch (InterruptedException ie)
            {
               // Ignore this for now.
            }
        }
        return null;
    }
}

Upvotes: 0

Related Questions