小工具之重试工具类

小工具之重试工具类,第1张

小工具之重试工具类 背景

项目中存在通过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;
    }
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5653806.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存