Multiple attempts to request an interface

Source: Internet
Author: User

In the interface request when we are generally a request, success is a failure is a success or failure, but sometimes we have to synchronize to determine the interface request success, such as the status of an order, order status for the entire process impact is very large, so we need to synchronize the request when necessary to succeed, So we need to request the interface multiple times until it succeeds or until n times, so we can look at the demo below to make three requests.

The code is as follows:

Import Com.alibaba.fastjson.JSON;
Import Com.google.gson.reflect.TypeToken;
Import Org.slf4j.Logger;
Import org.slf4j.LoggerFactory;
Import Org.springframework.stereotype.Service;

Import Javax.annotation.PreDestroy;
Import Java.util.HashMap;
Import Java.util.Map;
Import java.util.concurrent.Callable;
Import java.util.concurrent.ExecutionException;
Import Java.util.concurrent.Future;
Import Java.util.concurrent.TimeUnit;

 /** * @author Wanghaidong * @data 2017/11/29 * * @Service ("Reassignorderservice") public class Rea Ssignorderserviceimpl implements Ireassignorderservice {Logger Logger = Loggerfactory.getlogger (reassignorderserv

        Iceimpl.class);
        private static final String Order_status_url = "/reassign";
        /** * Maximum number of attempts */private final static int max_retry = 3;

        /** * thread pool */private volatile standardthreadexecutor executor = null; /** * thread Pool initialization */private void init () {if (null = = Executor) {SYNCHR Onized (Logger) {if (null = = Executor) {executor = new Standardthreadexecuto
                        R (1, Timeunit.minutes, 20000, New Namethreadfactory ("Orderpool-query-reassign-status"));
                    Executor.allowcorethreadtimeout (TRUE);
}
                }
            }
        }
        /** * Hook, close the thread pool */@PreDestroy private void Destroy () {if (executor
            ! = null) {Executor.shutdown (); }} @Override public int orderreassignstatus (String orderno) {if (null = = executor)
            {init ();
            } String IP = "XXX";
            String url = new StringBuilder (IP). Append (Reassignorderserviceimpl.order_status_url). toString ();
            map<string, object> params = new hashmap<> (1);

            Params.put ("OrderNo", OrderNo);
            Logger.info ("Request url:{}, request parameter param:{}", url, params);

            Long beginTime = System.currenttimemillis ();
            String Res;

            Responseresult<?> Responseresult;
                for (int i = 0; i < reassignorderserviceimpl.max_retry; i++) {res = this.executequery (URL, params); Logger.info ("Request returns result res:{}, interface time consuming times:{}ms, number of attempts to request Trytimes:{} ", Res, (System.currenttimemillis ()-beginTime), i);
                    try {if (null = = res) {continue; } else {Responseresult = Gsonutils.jsontobean (res, new typetoken<responseresult<object>&
                        gt; () {}.gettype ()); int code = (Null = = Responseresult?)
                        ResponseCodeEnum.RESPONSE_FAILD.getCode (): Responseresult.getcode ());
                        if (Code = = ResponseCodeEnum.RESPONSE_FAILD.getCode ()) {continue; } Boolean statusflag = (Code = = ResponseCodeEnum.RESPONSE_SUCCESS.getCode () && (null! = RE
                        Sponseresult.getdata () && null! = Responseresult.getdata (). Getneworderno ()));
                        if (Statusflag) {return ReassignOrderEnum.REASSIGN_ORDER.getCode ();
                     } else {       return ReassignOrderEnum.NOT_REASSIGN_ORDER.getCode (); }}} catch (Exception e) {logger.error ("Request time-consuming Times:{}ms", (syste
                M.currenttimemillis ()-beginTime), E);
        }} return ReassignOrderEnum.FAIL.getCode ();
        }/** * Request Execution method * * @param URL * @param params * @return */
            private string executeQuery (string url, map<string, object> params) {string res = null;
                future<string> result = This.executor.submit (new callable<string> () {@Override
                    Public String Call () {String res = Httputil.getintance (). Post (URL, params);
                return res;
            }
            });
            Boolean flag = false; while (!flag) {try {if (Result.isdone ()) {flag = true;
                    res = Result.get ();
                    }} catch (Exception e) {logger.error ("change state", e);
                Break
        }} return res; }
    }

In peacetime we will use multiple requests for the interface, although the above code is not the best way to implement, but the idea should be similar.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.