Finch 通过 .cache() 扩展方法提供路由级缓存。缓存的响应无需重新运行控制器。
router
.get('/api/products', ProductController().index)
.cache(duration: Duration(minutes: 10));
| 参数 |
类型 |
描述 |
duration |
Duration |
缓存有效期 |
cacheSource |
CacheSource |
memory 或 file(默认:memory) |
cacheType |
CacheParam |
如何确定缓存键 |
| 值 |
描述 |
CacheParam.all |
所有请求视为同一个(共享缓存) |
CacheParam.user |
每个用户独立缓存 |
CacheParam.params |
每个参数组合独立缓存 |
CacheParam.userAndParams |
用户和参数的组合 |
// 内存缓存(默认)——更快,重启后消失
.cache(
duration: Duration(hours: 1),
cacheSource: CacheSource.memory,
)
// 磁盘缓存——较慢,重启后保留
.cache(
duration: Duration(hours: 24),
cacheSource: CacheSource.file,
)
// 首页:所有人相同,5 分钟
router
.get('/home', HomeController().index)
.cache(
duration: Duration(minutes: 5),
cacheType: CacheParam.all,
);
// 仪表板:每用户独立缓存,30 分钟
router
.get('/dashboard', DashboardController().index)
.cache(
duration: Duration(minutes: 30),
cacheType: CacheParam.user,
);
// 搜索:基于查询参数,2 分钟
router
.get('/search', SearchController().results)
.cache(
duration: Duration(minutes: 2),
cacheType: CacheParam.params,
);
// 清除所有缓存
RouteCache.clearAllCache();
// 清除特定路由的缓存
RouteCache.clearCache('/api/products');