Flutter缓存管理插件vyuh_cache的使用
Flutter缓存管理插件vyuh_cache的使用

Vyuh Framework
构建模块化、可扩展、CMS驱动的Flutter应用程序
Vyuh Cache 💾
Vyuh框架的应用程序轻量级、灵活的缓存解决方案。提供基于时间的缓存,并支持可插拔的存储后端。非常适合减少API调用、提高应用性能和管理临时数据。
功能 ✨
- 基于时间的缓存:自动过期(TTL) ⏱️
- 类型安全:泛型实现以确保类型安全 🛡️
- 可插拔存储:内置内存存储,具有可扩展的存储接口 💾
- 异步API:所有操作均支持异步操作 ⚡
- 值生成:内置支持生成缺失的缓存值 🔄
- 过期处理:自动清理已过期条目 🧹
安装 📦
在`pubspec.yaml`文件中添加以下依赖:dependencies:
vyuh_cache: any
使用 💡
基本使用
创建一个带有内存存储的缓存实例:// 创建一个带有内存存储的缓存实例
final cache = Cache(
CacheConfig(
storage: MemoryCacheStorage<String>(),
ttl: Duration(minutes: 5),
),
);
// 存储一个值
await cache.set('greeting', 'Hello, World!');
// 检查键是否存在
if (await cache.has('greeting')) {
// 获取值
final value = await cache.get('greeting');
print(value); // Hello, World!
}
值生成
获取值并自动生成缺失的值:// 获取值并自动生成缺失的值
final value = await cache.build(
'user-123',
generateValue: () async {
// 耗时操作(例如API调用)
return await fetchUserFromApi('123');
},
);
缓存管理
删除特定条目:// 删除特定条目
await cache.remove('old-key');
清空所有条目:
// 清空所有条目
await cache.clear();
自定义存储
实现`CacheStorage`接口以支持自定义存储后端:class RedisStorage<T> implements CacheStorage<T> {
@override
Future<CacheEntry<T>?> get(String key) async {
// 实现Redis的get方法
}
@override
Future<void> set(String key, CacheEntry<T> value) async {
// 实现Redis的set方法
}
// ... 实现其他方法
}
最佳实践 🎯
- 选择合适的TTL:根据数据波动性设置TTL
- 错误处理:始终处理潜在的缓存未命中
- 类型安全:使用特定类型而不是动态类型
- 内存管理:清除未使用的缓存条目
- 存储选择:根据使用场景选择适当的存储方式
了解更多 📚
- 访问 docs.vyuh.tech 查看详细文档
- 查看 GitHub仓库
- 在 问题跟踪器 上报告问题
由 Vyuh 制作❤️
示例代码
// ignore_for_file: avoid_print
import 'dart:async';
import 'package:vyuh_cache/vyuh_cache.dart';
// 模拟API客户端
class ApiClient {
Future<String> fetchUserData(String id) async {
// 模拟API延迟
await Future.delayed(const Duration(seconds: 1));
return 'User data for ID: $id';
}
Future<Map<String, dynamic>> fetchProductDetails(String productId) async {
await Future.delayed(const Duration(milliseconds: 800));
return {
'id': productId,
'name': 'Product $productId',
'price': 99.99,
};
}
}
void main() async {
// 初始化API客户端
final apiClient = ApiClient();
// 示例1:基本字符串缓存
print('\n=== 基本字符串缓存示例 ===');
final stringCache = Cache(
CacheConfig(
storage: MemoryCacheStorage<String>(),
ttl: const Duration(minutes: 5),
),
);
// 存储并检索简单的字符串
await stringCache.set('greeting', 'Hello, World!');
if (await stringCache.has('greeting')) {
final greeting = await stringCache.get('greeting');
print('缓存问候语: $greeting');
}
// 示例2:带自动生成功能的用户数据缓存
print('\n=== 带自动生成功能的用户数据缓存示例 ===');
final userCache = Cache(
CacheConfig(
storage: MemoryCacheStorage<String>(),
ttl: const Duration(minutes: 10),
),
);
// 函数演示多次请求
Future<void> getUserData(String userId) async {
final userData = await userCache.build(
'user-$userId',
generateValue: () => apiClient.fetchUserData(userId),
);
print(
'用户数据 (来自${await userCache.has('user-$userId') ? '缓存' : 'API'}): $userData');
}
// 第一次请求 - 将从API获取
await getUserData('123');
// 第二次请求 - 将从缓存获取
await getUserData('123');
// 示例3:复杂对象缓存(Map)
print('\n=== 复杂对象缓存示例 ===');
final productCache = Cache(
CacheConfig(
storage: MemoryCacheStorage<Map<String, dynamic>>(),
ttl: const Duration(minutes: 15),
),
);
// 获取并缓存产品详情
final productId = 'PROD-001';
final productDetails = await productCache.build(
'product-$productId',
generateValue: () => apiClient.fetchProductDetails(productId),
);
print('产品详情: $productDetails');
// 示例4:缓存管理
print('\n=== 缓存管理示例 ===');
// 列出字符串缓存中的所有键
final keys = await stringCache.config.storage.keys();
print('字符串缓存中的当前键: $keys');
// 移除特定条目
await stringCache.remove('greeting');
print(
'移除问候语后 - 是否存在: ${await stringCache.has('greeting')}');
// 清空整个缓存
await stringCache.clear();
print(
'清空后 - 键的数量: ${(await stringCache.config.storage.keys()).length}');
// 示例5:错误处理
print('\n=== 错误处理示例 ===');
try {
await userCache.build(
'error-user',
generateValue: () => throw Exception('无法获取用户数据'),
);
} catch (e) {
print('处理错误: $e');
}
// 示例6:TTL演示
print('\n=== TTL演示 ===');
final shortCache = Cache(
CacheConfig(
storage: MemoryCacheStorage<String>(),
ttl: const Duration(seconds: 2), // 用于演示的极短TTL
),
);
await shortCache.set('quick-value', '这将很快过期');
print('初始值是否存在: ${await shortCache.has('quick-value')}');
await Future.delayed(const Duration(seconds: 3));
print(
'TTL到期后 - 值是否存在: ${await shortCache.has('quick-value')}');
}
更多关于Flutter缓存管理插件vyuh_cache的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
1 回复