0
点赞
收藏
分享

微信扫一扫

OkHttp3 阶梯延时重试请求HTTP接口实现方案

waaagh 2022-03-31 阅读 47
java
   /**
     * 序列化格式
     */
    private static final MediaType JSON
            = MediaType.get("application/json; charset=utf-8");

    /**
     * 最大重试次数.
     */
    private static final Integer maxRetry = 10;

    /**
     * 重试间隔.
     */
    private static final Integer retryInterval = 10;


    /**
     * http client.
     */
    private static OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(60, TimeUnit.SECONDS)
            .writeTimeout(60, TimeUnit.SECONDS)
            .readTimeout(60, TimeUnit.SECONDS)
            .build();


    /**
     * PSOT 请求.
     * @param url
     * @param req
     * @return
     */
    private static Map<String, Object> postInvoke(String url, Map<String, Object> req) {
        RequestBody body = RequestBody.create(JSON, JSONUtil.toJsonStr(req));
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        Response response = null;
        try {
            response = client.newCall(request).execute();
            int tryNum = 1;
            while ((response == null || !response.isSuccessful()) && tryNum <= maxRetry) {
                log.info("Invoke service is not successful - {}", tryNum);
                try {
                    // 阶梯延时重试.
                    int delayTimes = retryInterval ^ tryNum;
                    log.info("Wait for {}", delayTimes);
                    Thread.sleep(delayTimes);
                } catch (final InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
                tryNum++;
                response = client.newCall(request).execute();
            }
            if (response.isSuccessful()) {
                return JSONUtil.toBean(response.body().string(), HashMap.class);
            } else {
                log.error("Call Remote service failed {},{}", response.code(), response.message());
            }
            return Maps.newHashMap();
        } catch (IOException e) {
            log.error("Call Remote service exception {}", e);
        } finally {
            if (response != null) {
                response.close();
            }
        }
        return Maps.newHashMap();
    }
举报

相关推荐

0 条评论