perf(network): 优化接口请求频次、重试与连接配置

- TimeManager: 显式刷新配置增加 10 秒节流,窗口内合并为一次补刷,不再 dispose 已发出的请求
- TimeConfigRepository: 显式刷新先失效内存缓存保证回源;重试改为指数退避 + 随机抖动,400 使用更长间隔,鉴权/404 等永久错误不再重试
- DeviceRepository: 配置缓存 TTL 2s->30s、系统设置 3s->1min;强制安装/应用列表/检查更新支持并发合并并改为 IO 线程交付;新增 scheduleIo/invalidateMemory
- StatisticsRepository: 统计缓存 3s->30s
- OkHttpManager: connect 10s/read 20s/write 20s/call 60s;按接口类型缓存 Retrofit 代理;复用全局 Gson;正式包记录慢请求与异常状态码
- GsonUtils: 开放全局 Gson 实例
This commit is contained in:
tongtong committed 2026-11-25 16:44:52 +08:00
1 parent dbd1b41b9d
commit d0d8ed583a
6 files changed
+190 -26

No files matched your search

@@ -43,6 +43,13 @@ public class GsonUtils {
return TypeToken.getParameterized(rawType, typeArguments).getType();
}
/**
* 复用全局 Gson 实例,保证网络解析与本地缓存解析使用同一套适配器配置。
*/
public static Gson getGson() {
return gson;
}
public static String toString(Object value) {
if (Objects.isNull(value)) {
return null;
@@ -1,15 +1,22 @@
package com.fuying.sn.core.data.remote;
import android.content.Context;
import android.os.SystemClock;
import android.util.Log;
import com.fuying.sn.BuildConfig;
import com.fuying.sn.core.common.gson.GsonUtils;
import com.fuying.sn.core.common.util.FileUtils;
import java.io.File;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import okhttp3.Cache;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory;
@@ -19,18 +26,34 @@ import retrofit2.converter.gson.GsonConverterFactory;
* 创建并持有仓库共用的 HTTP 客户端和 Retrofit 配置。
*/
public final class OkHttpManager {
private static final int TIME_OUT = 30;
private static final String TAG = "OkHttpManager";
private static final long CACHE_SIZE = 16L * 1024 * 1024;
private static final int CONNECT_TIME_OUT_SECONDS = 10;
private static final int READ_TIME_OUT_SECONDS = 20;
private static final int WRITE_TIME_OUT_SECONDS = 20;
private static final int CALL_TIME_OUT_SECONDS = 60;
/**
* 超过该耗时的请求即使成功也记录日志,用于排查弱网与限流。
*/
private static final long SLOW_REQUEST_THRESHOLD_MS = 3000L;
private final OkHttpClient client;
private final Retrofit retrofit;
/**
* Retrofit 的动态代理创建有一定开销,按接口类型缓存,避免每次请求都重新创建。
*/
private final ConcurrentHashMap<Class<?>, Object> apiCache = new ConcurrentHashMap<>();
public OkHttpManager(Context context) {
OkHttpClient.Builder builder = new OkHttpClient.Builder()
.connectTimeout(TIME_OUT, TimeUnit.SECONDS)
.writeTimeout(TIME_OUT, TimeUnit.SECONDS)
.readTimeout(TIME_OUT, TimeUnit.SECONDS)
.connectTimeout(CONNECT_TIME_OUT_SECONDS, TimeUnit.SECONDS)
.writeTimeout(WRITE_TIME_OUT_SECONDS, TimeUnit.SECONDS)
.readTimeout(READ_TIME_OUT_SECONDS, TimeUnit.SECONDS)
// 限制整次调用的总耗时,避免重试叠加后线程被长时间占用
.callTimeout(CALL_TIME_OUT_SECONDS, TimeUnit.SECONDS)
.retryOnConnectionFailure(true);
// 慢请求、非 2xx 状态码在正式包也记录,其余请求只记耗时统计
builder.addInterceptor(createMonitorInterceptor());
if (BuildConfig.DEBUG) {
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
@@ -41,14 +64,40 @@ public final class OkHttpManager {
retrofit = new Retrofit.Builder()
.client(client)
.baseUrl(BuildConfig.ROOT_URL)
.addConverterFactory(GsonConverterFactory.create())
// 复用全局 Gson,保证网络与本地缓存使用同一套适配器
.addConverterFactory(GsonConverterFactory.create(GsonUtils.getGson()))
.addCallAdapterFactory(RxJava3CallAdapterFactory.create())
.build();
}
@SuppressWarnings("unchecked")
public <T> T create(Class<T> api) {
return retrofit.create(api);
Object cached = apiCache.get(api);
if (cached != null) {
return (T) cached;
}
T created = retrofit.create(api);
Object existing = apiCache.putIfAbsent(api, created);
return existing == null ? created : (T) existing;
}
private Interceptor createMonitorInterceptor() {
return chain -> {
long start = SystemClock.elapsedRealtime();
Request request = chain.request();
Response response = null;
try {
response = chain.proceed(request);
return response;
} finally {
long cost = SystemClock.elapsedRealtime() - start;
int code = response == null ? -1 : response.code();
boolean failed = code < 200 || code >= 300;
if (BuildConfig.DEBUG || failed || cost >= SLOW_REQUEST_THRESHOLD_MS) {
Log.e(TAG, "request: " + request.method() + " " + request.url()
+ ", code = " + code + ", cost = " + cost + "ms");
}
}
};
}
}
@@ -66,7 +66,8 @@ import okhttp3.MultipartBody;
public final class DeviceRepository {
private static final String TAG = "DeviceRepository";
private static final long DEFAULT_CACHE_EXPIRE = TimeUnit.SECONDS.toMillis(2);
// 管控配置的显式刷新会先失效内存缓存,这里的 TTL 只用于页面等非强制读取
private static final long DEFAULT_CACHE_EXPIRE = TimeUnit.SECONDS.toMillis(30);
private static final long SN_INFO_CACHE_TTL_MS = TimeUnit.HOURS.toMillis(24);
private static final long SN_INFO_OTHER_STATUS_TTL_MS = TimeUnit.SECONDS.toMillis(30);
private static final long CACHE_EXPIRE_ONE_MINUTE = TimeUnit.MINUTES.toMillis(1);
@@ -352,6 +353,30 @@ public final class DeviceRepository {
.observeOn(AndroidSchedulers.mainThread());
}
/**
* 后台链路专用:网络结果直接在 IO 线程交付,避免无谓地主线程唤醒。
*/
public <T> Observable<T> scheduleIo(Observable<T> observable) {
return observable
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.io());
}
/**
* 无缓存接口的并发合并:同一时刻的重复订阅共享一次请求,结果不写入缓存。
*/
public <T> Observable<T> scheduleShared(String key, Observable<T> network) {
return scheduleIo(Observable.defer(() -> joinInFlight(key, network, value -> {
})));
}
/**
* 仅失效内存缓存,保留磁盘缓存作为离线兜底;用于需要立即回源的显式刷新。
*/
public void invalidateMemory(String key) {
CACHE_MANAGER.removeCache(key);
}
/**
* 设备信息优先使用内存缓存;成功网络响应写入磁盘,其他响应短时缓存并移除磁盘副本。
*/
@@ -381,13 +406,13 @@ public final class DeviceRepository {
}
/**
* 页面读取系统设置时复用三秒内存缓存,并在内存未命中时使用磁盘与网络两级数据。
* 页面读取系统设置时复用一分钟内存缓存,并在内存未命中时使用磁盘与网络两级数据。
*/
public Observable<BaseResponse<SystemSettingsSet>> getSettingControl() {
return withMultiLevelCache(getSettingsApi().getSetting(DeviceIdUtils.getSerial()),
UrlAddress.GET_SETTINGS, new TypeToken<BaseResponse<SystemSettingsSet>>() {
}.getType(),
TimeUnit.SECONDS.toMillis(3));
CACHE_EXPIRE_ONE_MINUTE);
}
/**
@@ -404,7 +429,7 @@ public final class DeviceRepository {
}
public Observable<BaseResponse<List<AppInfo>>> getForceInstallControl() {
return schedule(getAppApi().getForceInstall(DeviceIdUtils.getSerial()));
return scheduleShared("force_install", getAppApi().getForceInstall(DeviceIdUtils.getSerial()));
}
public Observable<BaseResponse<BrowserApiData>> getBrowserControl() {
@@ -420,7 +445,7 @@ public final class DeviceRepository {
}
public Observable<BaseResponse<List<AppInfo>>> getQueryAllAppControl() {
return schedule(getAppApi().getAllApp(DeviceIdUtils.getSerial()));
return scheduleShared("query_all_app", getAppApi().getAllApp(DeviceIdUtils.getSerial()));
}
public Observable<BaseResponse<AppletQRCode>> getQRCodeApiControl() {
@@ -550,8 +575,9 @@ public final class DeviceRepository {
}
public Observable<BaseResponse<AppInfo>> checkAppUpdate(String packageName, String versionCode) {
return schedule(getAppApi().getAppUpdate(packageName, versionCode,
PlatformUtils.getPlatformCode()));
// 调用方均为后台更新链路,合并并发重复请求并保持在 IO 线程交付
return scheduleShared("check_app_update:" + packageName + ":" + versionCode,
getAppApi().getAppUpdate(packageName, versionCode, PlatformUtils.getPlatformCode()));
}
public Observable<BaseResponse> reportDeviceInfo(String address, String machine,
@@ -20,8 +20,8 @@ import io.reactivex.rxjava3.core.Observable;
*/
public class StatisticsRepository {
// 使用统计的内存缓存有效期为三秒,未过期时直接复用结果。
private static final long CACHE_TTL_MS = 3 * 1000L;
// 使用统计属于非强实时数据:内存缓存 30 秒,避免页面切换/重进时重复回源。
private static final long CACHE_TTL_MS = 30 * 1000L;
private static volatile StatisticsRepository INSTANCE;
@@ -11,6 +11,7 @@ import com.fuying.sn.core.data.dto.device.SnInfo;
import com.fuying.sn.core.data.dto.time.SnTimeControlInfo;
import com.fuying.sn.core.common.config.CommonConfig;
import com.fuying.sn.core.data.repository.DeviceRepository;
import com.fuying.sn.core.data.remote.UrlAddress;
import com.fuying.sn.core.common.gson.GsonUtils;
import com.fuying.sn.core.data.local.db.time.AppRemainingEntity;
import com.fuying.sn.core.data.local.db.time.AppTimeControlEntity;
@@ -20,13 +21,16 @@ import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.fuying.sn.core.data.local.prefs.KVStore;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.Scheduler;
import io.reactivex.rxjava3.schedulers.Schedulers;
import retrofit2.HttpException;
/**
* 时间管控配置仓库:统一负责服务端配置的拉取、本地缓存与失败重试。
@@ -52,8 +56,11 @@ public class TimeConfigRepository {
public static final String GLOBAL_REMAINING_TIME_KEY = "GLOBAL_REMAINING_TIME_KEY";
public static final String SN_INFO = "sn_info_key";
private static final long RETRY_INTERVAL = 60; // 重试间隔(秒)
private static final long RETRY_BASE_INTERVAL_MS = TimeUnit.MINUTES.toMillis(1); // 首次重试间隔
private static final long RETRY_MAX_INTERVAL_MS = TimeUnit.MINUTES.toMillis(10); // 退避上限
private static final long RETRY_TOO_FREQUENT_INTERVAL_MS = TimeUnit.MINUTES.toMillis(5); // 限流码退避
private static final int MAX_RETRY_COUNT = 10; // 最大重试次数,超过后停止重试
private static final Random RETRY_RANDOM = new Random();
/**
* 数据库写调度器:单线程保证 clear + insert 等组合操作的提交顺序。
@@ -239,6 +246,18 @@ public class TimeConfigRepository {
* @return 每处理一条未抛异常的响应发射 true,不代表业务成功或全部请求已结束
*/
public Observable<Boolean> fetchConfig() {
return fetchConfig(false);
}
/**
* @param forceRefresh true 时先失效内存中的两级管控配置,保证显式刷新一定回源;
* 磁盘缓存保留,作为离线时的兜底数据
*/
public Observable<Boolean> fetchConfig(boolean forceRefresh) {
if (forceRefresh) {
DeviceRepository.getInstance().invalidateMemory(UrlAddress.SN_TIME_CONTROL);
DeviceRepository.getInstance().invalidateMemory(UrlAddress.APP_TIME_CONTROL);
}
Observable<Boolean> sn =
DeviceRepository.getInstance().getSnTimeControlObservable()
.map(resp -> {
@@ -284,14 +303,46 @@ public class TimeConfigRepository {
private Observable<Boolean> retryConfigRequest(Observable<Boolean> request) {
return request.retryWhen(errors -> errors
.zipWith(Observable.range(1, MAX_RETRY_COUNT + 1), (error, attempt) -> {
if (attempt > MAX_RETRY_COUNT) {
if (attempt > MAX_RETRY_COUNT || !isRetryable(error)) {
throw error;
}
Log.e(TAG, "Config fetch failed, scheduling retry " + attempt
+ "/" + MAX_RETRY_COUNT, error);
return attempt;
long delay = retryDelayMillis(error, attempt);
Log.e(TAG, "Config fetch failed, retry " + attempt + "/" + MAX_RETRY_COUNT
+ " after " + delay + "ms", error);
return delay;
})
.concatMap(attempt -> Observable.timer(RETRY_INTERVAL, TimeUnit.SECONDS)));
.concatMap(delay -> Observable.timer(delay, TimeUnit.MILLISECONDS)));
}
/**
* 只重试可恢复的错误:网络异常、服务端 5xx/408/429 以及业务限流 400。
* 鉴权失败、接口不存在等永久错误直接失败,避免无意义地重试十次。
*/
private boolean isRetryable(Throwable error) {
if (error instanceof ConfigRetryException) {
return true;
}
if (error instanceof HttpException) {
int code = ((HttpException) error).code();
return code == 400 || code == 408 || code == 429 || code >= 500;
}
return error instanceof IOException;
}
/**
* 指数退避 + 随机抖动,避免大量设备同一时刻集中重试。
*/
private long retryDelayMillis(Throwable error, int attempt) {
long delay;
if (error instanceof ConfigRetryException) {
// 业务码 400 表示请求过于频繁,继续用短间隔重试只会延长限流时间
delay = RETRY_TOO_FREQUENT_INTERVAL_MS;
} else {
long exponential = RETRY_BASE_INTERVAL_MS << Math.min(attempt - 1, 4);
delay = Math.min(exponential, RETRY_MAX_INTERVAL_MS);
}
long jitter = (long) (delay * 0.2 * RETRY_RANDOM.nextDouble());
return delay + jitter;
}
// --- 内部处理:单级响应更新 ---
@@ -72,6 +72,10 @@ import io.reactivex.rxjava3.schedulers.Schedulers;
*/
public class TimeManager {
private static final String TAG = "TimeManager";
/**
* 两次显式刷新配置的最小间隔:推送、跨天、安装上报等触发可能连续到达。
*/
private static final long CONFIG_REFRESH_MIN_INTERVAL_MS = TimeUnit.SECONDS.toMillis(10);
@SuppressLint("StaticFieldLeak")
private static TimeManager sInstance;
@@ -89,6 +93,18 @@ public class TimeManager {
*/
private final Handler mMainHandler = new Handler(Looper.getMainLooper());
/**
* 配置刷新的节流状态:窗口内的刷新请求合并为一次补刷。
*/
private long mLastConfigRefreshAt;
private volatile boolean mConfigRefreshPending;
private final Runnable mPendingRefreshRunnable = () -> {
if (!mConfigRefreshPending) {
return;
}
refreshTimeControl();
};
private SnTimeControlInfo mSnTimeControlInfo;
@@ -783,18 +799,31 @@ public class TimeManager {
// --- 网络接口请求(委托给 TimeConfigRepository) ---
public synchronized void refreshTimeControl() {
long now = System.currentTimeMillis();
long elapsed = now - mLastConfigRefreshAt;
if (elapsed < CONFIG_REFRESH_MIN_INTERVAL_MS) {
// 节流窗口内不重复发起:只登记一次补刷,避免把已发出的请求 dispose 后立刻重发
mConfigRefreshPending = true;
mMainHandler.removeCallbacks(mPendingRefreshRunnable);
mMainHandler.postDelayed(mPendingRefreshRunnable, CONFIG_REFRESH_MIN_INTERVAL_MS - elapsed);
Log.e(TAG, "refreshTimeControl: throttled. elapsed = " + elapsed);
return;
}
mLastConfigRefreshAt = now;
mConfigRefreshPending = false;
mMainHandler.removeCallbacks(mPendingRefreshRunnable);
// 策略变更和跨天需要重新读取配置,旧任务可能还在等待重试。
if (isConfigFetchRunning()) {
mConfigRetryDisposable.dispose();
}
fetchConfigWithRetry();
fetchConfigWithRetry(true);
}
public void getTimeControl() {
Log.e(TAG, "Syncing time control config from server...");
// 关键:必须订阅 Observable,否则冷 Observable 不会执行内部网络请求,配置无法同步。
// 直接复用 fetchConfigWithRetry 完成订阅与失败重试。
fetchConfigWithRetry();
fetchConfigWithRetry(false);
}
/**
@@ -909,12 +938,12 @@ public class TimeManager {
* 刷新配置(含失败自动重试):委托给 TimeConfigRepository,
* 由其统一管理重试间隔与最大次数,替代原先手写的重试定时器。
*/
private synchronized void fetchConfigWithRetry() {
private synchronized void fetchConfigWithRetry(boolean forceRefresh) {
// 初始化、页面和联网回调共享同一轮同步,包括等待重试的时间。
if (isConfigFetchRunning()) {
return;
}
Disposable disposable = mConfigRepository.fetchConfig()
Disposable disposable = mConfigRepository.fetchConfig(forceRefresh)
.observeOn(AndroidSchedulers.mainThread())
.to(BackgroundRequests.submit(new DisposableObserver<Boolean>() {
@Override
@@ -962,6 +991,8 @@ public class TimeManager {
}
public synchronized void onDestroy() {
mMainHandler.removeCallbacks(mPendingRefreshRunnable);
mConfigRefreshPending = false;
ReceiverCompat.unregisterReceiver(mContext, mTimeChangedReceiver);
mTimeChangedReceiver = null;
if (mPersistedConfigDisposable != null && !mPersistedConfigDisposable.isDisposed()) {