栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 前沿技术 > 大数据 > 大数据系统

小工具之重试工具类

小工具之重试工具类

背景

项目中存在通过http请求调用其他第三方接口,需要根据调用返回的状态码进行重试。

class Retry{

     
    public static final int MAX_RETRIES = 3;

    
    public static final int MAX_WAIT_INTERVAL = 3;


    public void retryDoGet(String url, String name) {
        int retries = 0;
        boolean retry = false;
        do {
            long start = System.currentTimeMillis();
            String result = HttpClient.get(url);
            //log.info("{}处理时间:{}/ms,结果:{}", name, System.currentTimeMillis() - start, result);
            if (StringUtils.isNotBlank(result)) {
                JSonObject r = JSON.parseObject(result);//返回结果根据自己的数据类型做解析
                if (r != null && r.getInteger("code") == 200) {
                    retry = false;
                } else {
                    retry = true;
                }
            } else {
                retry = true;
            }
            if (retry) {
                try {
                    long waitTimeExp = Math.min(MathUtil.getWaitTimeExp(retries), MAX_WAIT_INTERVAL) * 1000;
                    //wait for next try
                    Thread.sleep(waitTimeExp);//1s 2s 4s
                    //log.error("{}失败, 重试次数: {}, 下次重试间隔时间: {}/ms", name, retries, waitTimeExp);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        } while (retry && (retries++ < MAX_RETRIES));
    }

}

class MathUtil {

    
    public static long getWaitTimeExp(Integer retryCount) {
        long waitTime = (long) Math.pow(2, retryCount);
        return waitTime;
    }

}

class HttpClient {

    public static String get(String url) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpGet httpget = new HttpGet(url);
            HttpResponse response = httpclient.execute(httpget);
            int status = response.getStatusLine().getStatusCode();
            if (status >= 200 && status < 300) {
                HttpEntity entity = response.getEntity();
                return entity != null ? EntityUtils.toString(entity, "utf-8") : null;
            } else {
                throw new ClientProtocolException("Unexpected response status: " + status);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (httpclient != null) httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/651672.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号