简体   繁体   中英

How to implement a retry After logic?

I was recently working on an application and have a use case where I return back a set of responses to clients eg ALLOW, DENY and PENDING.

Let's say if the response returned by the service is PENDING, I want clients to retry back after a given interval. This interval is given by the Server.

I want to know what are best practices around modeling my service response for such a use case. I was thinking to have the response something like this:

String Decision; long retryIntervalInMinutes;

but then for decision ALLOW and DENY, retryIntervalInMinutes doesn't makes sense and should not be returned.

One way to model this:

Decision - Abstract class Allow extends Decision Deny extends Decision Pending extends Decision

Only Pending object will contain the retryIntervalInMinutes.

But this comes with its own problems as how client will decipher such a response without using instanceof or type casting etc.

Or is there any other better way to model such a response ?

Why not have getRetryInterval() method in your abstract Decision class that returns 0 by default and override it in Pending concrete class?

Also, you could have a method isEntryAllowed() that would return true only in Allow class.

Your clients could use just these two methods to discover what the answer means, no neeed for isntanceof .

Simple enum would be even better, since responses are immutable singletons:

public enum Response {

    ALLOW, DENY, RETRY; 

    public boolean isEntryAllowed() {
        return this == ALLOW;
    }

    public boolean isRetryAllowed() {
        return this == RETRY;
    }

    public int getRetryInterval() {
        return this == RETRY ? 42 : -1;
    }
}

Clients get some Response instance and can use it's methods to find out what the response means:

Response respone = sendRequestToServer();
if (response.isEntryAllowed()) {
  // cool! let's move on!
} else if (response.isRetryAllowed()) {
   retryAfter(response.getRetryInterval());
} else {
  // too bad, need to find another server or sth
}

Zero is also a number. If your classes have a retry-delay attribute, which is the duration that should be waited, you can have that attribute be zero for the cases when there should be no delay.

For a web service communicating the delay to the client, the standard HTTP header named Retry-After is the appropriate medium.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM