CacheStrategy<V> class

统一缓存策略

根据 CacheMode 选择不同的缓存实现:

使用示例:

// 仅内存缓存
final memoryCache = CacheStrategy<UserEntity>(
  mode: CacheMode.memory,
  maxSize: 100,
);

// 持久化缓存
final persistentCache = CacheStrategy<UserEntity>(
  mode: CacheMode.persistent,
  cacheKey: 'user_cache',
  maxSize: 100,
  expiration: Duration(hours: 1),
  fromJson: UserEntity.fromJson,
  toJson: (e) => e.toJson(),
);

// 混合模式(推荐)
final hybridCache = CacheStrategy<UserEntity>(
  mode: CacheMode.hybrid,
  cacheKey: 'user_cache',
  maxSize: 100,
  expiration: Duration(hours: 1),
  fromJson: UserEntity.fromJson,
  toJson: (e) => e.toJson(),
);

Constructors

CacheStrategy({required int maxSize, String? cacheKey, Duration? expiration, V fromJson(Map<String, dynamic> json)?, Map<String, dynamic> toJson(V value)?, CacheMode mode = CacheMode.persistent, bool autoRegister = true})

Properties

autoRegister bool
是否自动注册到 CacheRegistry
final
cacheKey String?
缓存 key 前缀(persistent/hybrid 模式必填)
final
diskSize int
获取磁盘缓存大小
no setter
expiration Duration?
过期时间(可选,仅 persistent/hybrid 模式有效)
final
fromJson → V Function(Map<String, dynamic> json)?
JSON 反序列化(persistent/hybrid 模式必填)
final
hashCode int
The hash code for this object.
no setterinherited
keys Iterable<String>
获取所有缓存的键
no setter
length int
获取缓存大小
no setter
maxSize int
最大缓存数量
final
memorySize int
获取内存缓存大小
no setter
mode CacheMode
缓存模式
final
runtimeType Type
A representation of the runtime type of the object.
no setterinherited
toJson Map<String, dynamic> Function(V value)?
JSON 序列化(persistent/hybrid 模式必填)
final

Methods

cleanExpired() Future<void>
清理过期数据(仅 persistent/hybrid 模式有效)
clear() Future<void>
清空所有缓存
containsKey(String key) bool
检查是否包含 key
evictMemoryToSize(int targetSize) → void
手动淘汰内存缓存到指定大小
get(String key) → V?
获取缓存数据
init() Future<void>
初始化(从磁盘恢复数据)
noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
put(String key, V value) Future<void>
存入缓存
putAll(Map<String, V> entries) Future<void>
批量存入
remove(String key) Future<V?>
移除指定 key
toString() String
A string representation of this object.
override

Operators

operator ==(Object other) bool
The equality operator.
inherited