Retrofit+Rxjava伺服器IP輪詢重試機制實現

weixin_34377065發表於2016-12-12

為了保證客戶端穩定性和網路容錯性,提升使用者體驗,在客戶端建立服務端IP輪詢及重試機制是十分有必要的,本文為我個人經驗總結,希望對你能有參考價值。

app在啟動時會請求一些配置資訊,其中就包括ip的路由表,將這份路由表儲存到本地,至於是sp還是物件持久化抑或是其他方式,可根據實際情況自行選擇。

因為專案網路層由Retrofit+Rxjava+Okhttp實現,Retrofit執行時無法改變baseUrl,即使可以通過反射的方式來改變baseUrl,也無法對已經生成的service物件起作用,而且我的專案中所有service物件都通過Dagger2注入,所以最終使用了這樣一種方式。

url交給UrlManager來管理

public class UrlManager {

    public static final String[] HOST_SITE = {"https://xxx/api/",xxx};
    public static final String[] HOST_WEB = {"https://xxx/",xxx};
    public static final String HOST_SITE_DEBUG = "https://xxx/api/";
    public static final String HOST_WEB_DEBUG = "https://xxx/";
    public static List<String> list;
    public static Random random = new Random();

    public static String getHostSite() {
        if (BuildConfig.IS_DEBUG) {
            return processUrl(HOST_SITE_DEBUG);
        } else {
            String host = getDynamicHost();
            if (!TextUtils.isEmpty(host)) return host;
            return HOST_SITE[random.nextInt(HOST_SITE.length)];
        }
    }

    @Nullable
    private static String getDynamicHost() {
        int index = (int) SPUtils.get(NeutronApplication.getContext(), Constants.URL, 0);
        if (list != null && list.size() > 0 && index < list.size())
            return list.get(index);
        return null;
    }

    public static String getHostWeb() {
        if (BuildConfig.IS_DEBUG) {
            return processUrl(HOST_WEB_DEBUG);
        } else {
            String host = getDynamicHost();
            if (!TextUtils.isEmpty(host)) return host;
            return HOST_WEB[random.nextInt(HOST_WEB.length)];
        }
    }

    public static void setHosts(List<String> list) {
        UrlManager.list = list;
        RxHelper.setCounterAttempts(list.size());
    }


    public static void updateUrlIndex(int i) {
        if (list != null && i >= list.size())
            i = 0;
        SPUtils.put(NeutronApplication.getContext(), Constants.URL, i);
    }

    public static void updateUrlIndex() {
        int o = (int) SPUtils.get(NeutronApplication.getContext(), Constants.URL, 0);
        updateUrlIndex(o + 1);
    }複製程式碼

app啟動時拉取到配置後設定UrlManager中的路由表,然後每次根據索引去路由表動態拿請求地址,那路由索引由誰來控制呢?
因為我將專案中的rxjava抽取了一層RxHelper,所以這件事就交給RxHelper來幹了,可以覆蓋所有的網路請求。

public class RxHelper {
    private static final int COUNTER_START = 0;
    private static int COUNTER_ATTEMPTS = 3;

    public static void setCounterAttempts(int counterAttempts) {
        COUNTER_ATTEMPTS = counterAttempts;
    }

    public static <T> rx.Observable.Transformer<T, T> handleResult() {
        return tObservable -> tObservable
                .flatMap(RxHelper::createData)
                .retryWhen(observable -> observable.compose(zipWithFlatMap()))
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io());
    }

    public static <T> rx.Observable.Transformer<T, T> handleResultWithOutRetryPolicy() {
        return tObservable -> tObservable.flatMap(RxHelper::createData)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io());
    }

    public static <T> Observable.Transformer<T, Long> zipWithFlatMap() {
        return observable ->
                observable.zipWith(Observable.range(COUNTER_START, COUNTER_ATTEMPTS),
                        (t, repeatAttempt) -> repeatAttempt)
                        .flatMap(new Func1<Integer, Observable<Long>>() {
                            @Override
                            public Observable<Long> call(Integer repeatAttempt) {
                                UrlManager.updateUrlIndex(repeatAttempt);
                                return Observable.timer(repeatAttempt * 200, TimeUnit.MILLISECONDS);
                            }
                        });
    }

    private static <T> Observable<T> createData(final T t) {
        return Observable.create(new Observable.OnSubscribe<T>() {
            @Override
            public void call(Subscriber<? super T> subscriber) {
                try {
                    subscriber.onNext(t);
                    subscriber.onCompleted();
                } catch (Exception e) {
                    LogUtils.logw("Rxhelper: " + e.toString());
                    subscriber.onError(e);
                }
            }
        });
    }
}複製程式碼

這樣在每次請求錯誤時,會遞增路由表索引,繼續下次請求,輪詢的間隔為Observable.timer(repeatAttempt * 200, TimeUnit.MILLISECONDS);
對RxJava的retryWhen不理解的同學請移步對RxJava中.repeatWhen()和.retryWhen()操作符的思考

之前也說了,retrofit不能修改baseUrl,反射的方式也不適合我的專案,至於利用builder生成新的retrofit物件的方式更不考慮了,那我是怎麼實現執行時修改請求地址的呢?別忘了okhttp是可以新增攔截器的,在OkHttpIntercepter中:

public class OkHttpInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        //配置request
        Request request = chain.request();
        Request.Builder requestBuilder = request.newBuilder();
        String url = UrlManager.getHostSite();
        Uri parse = Uri.parse(url);
        String host = parse.getHost();
        HttpUrl httpUrl = request.url().newBuilder().host(host).build();
        requestBuilder.url(httpUrl);
        Response.Builder responseBuilder = chain.proceed(requestBuilder.build()).newBuilder();
        Response response = responseBuilder.build();
        return response;
    }複製程式碼

攔截請求的url,修改其host,這樣整個流程就ok了,http的各種錯誤碼的處理也是可以在攔截器中統一處理的,至於其他健壯性的考慮此處就不做過多闡述了。

有同學問我,如果想處理最後一次error通知怎麼辦呢?可以這樣做,修改過的RxHelper如下:

    public class RxHelper {
    private static final int COUNTER_START = 0;
    private static int COUNTER_ATTEMPTS = 3;

    public static void setCounterAttempts(int counterAttempts) {
        COUNTER_ATTEMPTS = counterAttempts;
    }

    public static <T> rx.Observable.Transformer<T, T> handleResult() {
        return tObservable -> tObservable
                .flatMap(RxHelper::createData)
                .retryWhen(error -> delayedRetry(error))
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io());
    }
    //貓膩主要在這個方法
    private static Observable<Object> delayedRetry(Observable<? extends Throwable> error) {
        return error.zipWith(Observable.range(COUNTER_START, COUNTER_ATTEMPTS + 1),
                (i, repeatAttempt) -> repeatAttempt)
                .flatMap(o -> {
                    UrlManager.updateUrlIndex(o);
                    LogUtils.logw("repeat: " + o);
                    return o < COUNTER_ATTEMPTS ? Observable.timer(o * 200, TimeUnit.MILLISECONDS)
                            : error.flatMap(Observable::error);
                });
    }

    public static <T> rx.Observable.Transformer<T, T> handleResultWithOutRetryPolicy() {
        return tObservable -> tObservable.flatMap(RxHelper::createData)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io());
    }

    private static <T> Observable<T> createData(final T t) {
        return Observable.create(new Observable.OnSubscribe<T>() {
            @Override
            public void call(Subscriber<? super T> subscriber) {
                try {
                    subscriber.onNext(t);
                    subscriber.onCompleted();
                } catch (Exception e) {
                    subscriber.onError(e);
                }
            }
        });
    }
}複製程式碼

相關文章