You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用dio_cache_interceptor缓存POST请求未提速,求优化方案

优化Dio缓存实现的建议

1. 修正缓存策略设置

你当前请求时用了CachePolicy.refresh,这个策略会强制每次发起网络请求并更新缓存,完全不会复用缓存数据,这就是重复请求耗时没减少的核心原因。

如果要实现类似Instagram的“先展示缓存、后台更新”的效果,改用CachePolicy.staleWhileRevalidate;如果不需要实时更新,仅用缓存提速,可改用CachePolicy.forceCache。

修改请求代码中的options:

options: cacheOptions.copyWith(policy: CachePolicy.staleWhileRevalidate).toOptions(),

2. 复用Dio实例

每次请求都新建Dio实例并添加拦截器,会带来不必要的性能开销,还可能导致缓存状态无法共享。建议全局初始化一次Dio:

// 全局初始化(比如在APP启动时)
final dio = Dio()
  ..interceptors.add(DioCacheInterceptor(options: cacheOptions));

// 后续请求直接复用这个dio实例
Future<List> fetchTotalDiaries(
    UserProfile userProfile, int currentPage) async {
  try {
    Map<String, dynamic> requestBody = {
      'user': userProfile.toJson(),
      'currentPage': currentPage,
      'offset': offset,
    };

    String requestBodyJson = jsonEncode(requestBody);
    final response = await dio.post(
      "https://diejlcrtffmlsdyvcagq.supabase.co/functions/~~~",
      data: requestBodyJson,
      options: cacheOptions.copyWith(policy: CachePolicy.staleWhileRevalidate).toOptions(),
    );

    if (response.statusCode == 200) {
      final data = response.data["data"];
      return data;
    }
  } catch (e) {
    print("fetchTotalDiaries --> $e");
  }
  return [];
}

3. 修正POST请求的缓存Key构建逻辑

你当前的keyBuilder仅用request.uri.toString()作为缓存Key,但POST请求的参数在请求体中,不同的请求体应该对应不同的缓存Key。如果不修改,会导致不同参数的请求共用同一个缓存,或者相同参数的请求无法命中缓存。

更新keyBuilder,将请求方法和请求体内容加入Key:

keyBuilder: (request) {
  // 拼接请求方法、URI和请求体,生成唯一Key
  final bodyStr = request.data?.toString() ?? '';
  return '${request.method}:${request.uri.toString()}:$bodyStr';
},

4. 改用持久化缓存存储

当前使用的MemCacheStore是内存级缓存,APP重启后缓存会丢失。如果要实现长期缓存效果,建议改用持久化存储,比如HiveCacheStore:

首先添加依赖:

dependencies:
  dio_cache_interceptor_hive_store: ^3.2.0

然后初始化Hive存储:

// 全局初始化(APP启动时)
final cacheStore = HiveCacheStore();
await cacheStore.init();

final cacheOptions = CacheOptions(
  store: cacheStore,
  // 其他配置保持不变
);

5. 验证缓存命中情况

可以添加拦截器日志,确认缓存是否生效:

// 在Dio拦截器中添加日志拦截器
dio.interceptors.add(LogInterceptor(responseBody: true));

请求时查看日志,如果看到[DioCacheInterceptor] Cache hit的日志,说明缓存生效。

内容的提问来源于stack exchange,提问作者Hyejung

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 22:14:53