패키지, 저장소 및 앱 카테고리 검색

패키지 상세v0.3.0

dio_http_cache

Flutter용 Dio HTTP 캐시 라이브러리, RxCache와 유사합니다. 디스크 캐시로는 sqflite를 사용하고, 메모리 캐시로는 google/quiver-dart/LRU 전략을 사용합니다.

AndroidiOSmacOS
30일 다운로드
1.6천
좋아요
248
Pub 점수
120

패키지 설치

flutter pub add dio_http_cache

패키지 개요

공개 정보를 바탕으로 생성한 선택 가이드입니다.

Dio HTTP Cache는 Flutter의 Dio HTTP 클라이언트용 캐시 라이브러리로, 메모리 및 디스크 기반 캐싱을 모두 제공합니다. 디스크에 지속적인 저장을 위해 sqflite를 사용하며, google/quiver-dart를 통해 LRU(최근 사용된 순서 기준) 전략을 구현하여 효율적인 메모리 관리를 합니다. 이 패키지는 HTTP 응답을 캐시함으로써 중복 네트워크 요청을 줄이고 앱 성능을 향상시키며 대역폭을 절약하는 데 도움을 줍니다. 오프라인 지원이 필요하거나 안정적인 데이터를 가진 자주 호출되는 API가 있는 앱에 적합합니다.

사용 사례

  • 네트워크 사용량을 줄이기 위해 API 응답 캐싱
  • 이전에 가져온 데이터에 대한 오프라인 액세스 활성화
  • 저지연으로 앱 성능 향상
  • 자주 액세스되는 데이터를 효율적으로 저장하기
  • 캐시된 응답을 통한 서버 부하 감소

주요 기능

  • sqflite를 사용한 디스크 캐싱
  • quiver-dart와 함께하는 LRU 메모리 캐시
  • 자동 요청/응답 캐싱
  • 사용자 지정 캐시 만료
  • GET 및 HEAD 요청을 지원합니다

적합한 대상

  • 자주 API 호출을 하는 앱
  • 오프라인 사용 가능한 애플리케이션
  • 성능 최적화된 네트워크 계층
  • 데이터 집약적인 모바일 앱
  • HTTP 요청에 Dio를 사용하는 개발자

고려 사항

  • sqflite 설정 및 권한이 필요합니다
  • 캐시 크기는 수동으로 관리해야 합니다
  • 대규모 이진 데이터에 적합하지 않습니다
  • GET/HEAD 메서드로 제한
  • 복잡한 요청에 대해 사용자 정의 캐시 키 로직이 필요할 수 있습니다

원본 README

연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.

dio-http-cache

Pub

中文介绍

Dio-http-cache is a cache library for Dio ( http client for flutter ), like Rxcache in Android.

Dio-http-cache uses sqflite as disk cache, and LRU strategy as memory cache.

Inspired by flutter_cache_manager.

Add Dependency
dependencies:
  dio_http_cache: ^0.3.x #latest version
QuickStart
  1. Add a dio-http-cache interceptor in Dio :

    dio.interceptors.add(DioCacheManager(CacheConfig(baseUrl: "http://www.google.com")).interceptor);
    
  2. Set maxAge for a request :

    Dio().get(
      "http://www.google.com",
      options: buildCacheOptions(Duration(days: 7)),
    );
    
The advanced
  1. Custom your config by buildCacheOptions :

    1. primaryKey: By default, host + path is used as the primaryKey, and you can also customize it.

    2. subKey: By default, query ( data or queryParameters) is used as subKey, and you can specify the subKey when it's necessary, for example:

      buildCacheOptions(Duration(days: 7), subKey: "page=1")
      
    3. maxAge: set the cache time. If the value is null or not setted, it will try to get maxAge and maxStale from response headers.

    4. maxStale: set stale time. When an error (like 500,404) occurs before maxStale, try to return cache.

      buildCacheOptions(Duration(days: 7), maxStale: Duration(days: 10))
      
    5. forceRefresh: false default.

      buildCacheOptions(Duration(days: 7), forceRefresh: true)
      
      1. Get data from network first.
      2. If getting data from network succeeds, store or refresh cache.
      3. If getting data from network fails or no network avaliable, try get data from cache instead of an error.
  2. Use "CacheConfig" to config default params

    1. baseUrl: it’s optional; If you don't have set baseUrl in CacheConfig, when you call deleteCache, you need provide full path like "https://www.google.com/search?q=hello", but not just "search?q=hello".
    2. encrypt / decrypt: these two must be used together to encrypt the disk cache data, you can also zip data here.
    3. defaultMaxAge: use Duration(day:7) as default.
    4. defaultaMaxStale: similar with DefaultMaxAge.
    5. databasePath: database path.
    6. databaseName: database name.
    7. skipMemoryCache: false defalut.
    8. skipDiskCache: false default.
    9. maxMemoryCacheCount: 100 defalut.
    10. defaultRequestMethod: use "POST" as default, it will be used in delete caches.
    11. diskStore: custom disk storage.
  3. How to clear expired cache

    • Just ignore it, that is automatic.

    • But if you insist : DioCacheManager.clearExpired();

  4. How to delete caches

    1. No matter what subKey is, delete local cache if primary matched.

      // Automatically parses primarykey from path
      _dioCacheManager.deleteByPrimaryKey(path, requestMethod: "POST"); 
      
    2. Delete local cache when both primaryKey and subKey matched.

      // delete local cache when both primaryKey and subKey matched.
      _dioCacheManager.deleteByPrimaryKeyAndSubKey(path, requestMethod: "GET"); 
      

      INPORTANT: If you have additional parameters when requesting the http interface, you must take them with it, for example:

      _dio.get(_url, queryParameters: {'k': keyword}, 
      	options: buildCacheOptions(Duration(hours: 1)))
      //delete the cache:
      _dioCacheManager.deleteByPrimaryKeyAndSubKey(_url, requestMethod: "GET", queryParameters:{'k': keyword}); 
      
      _dio.post(_url, data: {'k': keyword}, 
      	options: buildCacheOptions(Duration(hours: 1)))
      //delete the cache:
      _dioCacheManager.deleteByPrimaryKeyAndSubKey(_url, requestMethod: "POST", data:{'k': keyword}); 
      
    3. Delete local cache by primaryKey and optional subKey if you know your primarykey and subkey exactly.

      // delete local cache by primaryKey and optional subKey
      _dioCacheManager.delete(primaryKey,{subKey,requestMethod});
      
  5. How to clear All caches (expired or not)

    _dioCacheManager.clearAll();
    
  6. How to know if the data come from Cache

    if (null != response.headers.value(DIO_CACHE_HEADER_KEY_DATA_SOURCE)) {
     	// data come from cache
    } else {
     	// data come from net
    }
    
Example for maxAge and maxStale
_dio.post(
	"https://www.exmaple.com",
	data: {'k': "keyword"},
	options:buildCacheOptions(
  		Duration(days: 3), 
  		maxStale: Duration(days: 7), 
	)
)
  1. 0 ~ 3 days : Return data from cache directly (irrelevant with network).
  2. 3 ~ 7 days:
    1. Get data from network first.
    2. If getting data from network succeeds, refresh cache.
    3. If getting data from network fails or no network avaliable, try get data from cache instead of an error.
  3. 7 ~ ∞ days: It won't use cache anymore, and the cache will be deleted at the right time.
License
Copyright 2019 Hurshi

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

카테고리

의존성

의존성 목록 7 개

소스 저장소

이 패키지를 사용하는 프로젝트