当前位置: 首页 > news >正文

这段代码中的 ttl是做什么的

const { create: createAxios } = require('axios').default;
const { setupCache } = require('axios-cache-interceptor');
const { log } = console;//
// Complete documentation at:
// https://axios-cache-interceptor.js.org/
//(async () => {const axios = setupCache(// creating axios instancecreateAxios({ baseURL: 'https://registry.npmjs.org/' }),// configuring the cache{ ttl: 99999, interpretHeader: true });const fetchedResponse = await axios.get('/axios-cache-interceptor');// fetchedResponse.cached == false//// The next request won't do a network request, because the response is already cached//const cachedResponse = await axios.get('/axios-cache-interceptor');// cachedResponse.cached == truelog(`First request was ${fetchedResponse.cached ? 'cached' : 'fetched'}`);log(`Second request was ${cachedResponse.cached ? 'cached' : 'fetched'}`);//// The interpretHeader option used a different strategy, see the received Cache-Control header// (server may return undefined if this is the first request in a while :))//log(`Fetched response Cache-Control: ${fetchedResponse.headers['cache-control']}`);log(`Fetched response Age: ${fetchedResponse.headers.age}`);const cacheInformation = await axios.storage.get(fetchedResponse.id);//// As you can see, the TTL used was the maxAge cache directive minus the Age header//log(`Cache TTL info: ${cacheInformation.ttl}`);//// If you disable the interpretHeader option you'll see that the TTL will be the default (99999)\n//// Remove the old cache by brute forceawait axios.storage.remove(fetchedResponse.id);const refetchedResponse = await axios.get('/axios-cache-interceptor', {cache: {// This time with interpretHeader disabledinterpretHeader: false}});const refetchedInformation = await axios.storage.get(refetchedResponse.id);log(`Third request TTL: ${refetchedInformation.ttl}`);
})().catch(console.error);

在这段使用 axios-cache-interceptor 的代码中,ttlTime To Live(生存时间) 的缩写,它决定了 缓存条目在内存中可以保留多久(单位:毫秒)


✅ 简单理解:

ttl = 缓存的有效期。过了这个时间,缓存就“过期”了,下次请求会重新从网络获取。


🔍 在代码中的具体作用

const axios = setupCache(createAxios({ baseURL: 'https://registry.npmjs.org/' }),{ ttl: 99999, interpretHeader: true } // ← 这里的 ttl
);

这里设置了两个关键配置:

配置项 作用
ttl: 99999 默认缓存有效期为 99,999 毫秒(约 100 秒)
interpretHeader: true 优先从 HTTP 响应头(如 Cache-ControlAge)中解析真实的缓存时间,而不是直接用 ttl

🧠 interpretHeader: true 时的逻辑(重点!)

interpretHeadertrue(默认值),ttl 只是“兜底值”,实际 TTL 会根据服务器返回的 HTTP 缓存头动态计算:

  1. 服务器返回:
    Cache-Control: max-age=300
    Age: 50
    
  2. 那么实际缓存时间 = max-age - Age = 300 - 50 = 250 秒
  3. 这个 250 秒会覆盖你设置的 ttl: 99999
  4. 所以你在日志中看到:
    log(`Cache TTL info: ${cacheInformation.ttl}`); 
    // 输出的是 250000(毫秒),不是 99999!
    

💡 这就是为什么文档说:
“The TTL used was the maxAge cache directive minus the Age header”


🔁 对比:interpretHeader: false

当你在第三次请求中关闭了 interpretHeader

const refetchedResponse = await axios.get('/...', {cache: { interpretHeader: false }
});

这时,完全忽略服务器的 Cache-Control,直接使用你配置的默认 ttl: 99999

所以日志输出:

log(`Third request TTL: ${refetchedInformation.ttl}`);
// 输出 99999(毫秒)

📌 总结:ttl 的作用

场景 ttl 的作用
interpretHeader: true(默认) 备用值:当服务器没返回有效缓存头时才用
interpretHeader: false 强制使用:所有请求都按这个时间缓存
单位 毫秒(ms)
默认值 如果不传 ttl,默认是 1000 * 60 * 5(5 分钟)

💡 最佳实践建议

  • 保留 interpretHeader: true:尊重服务器的缓存策略,更符合 HTTP 标准
  • ⚠️ ttl 设为合理兜底值:比如 60_000(1分钟),防止无缓存头的接口永久缓存
  • ❌ 不要盲目设超大 ttl(如 999999999),可能导致数据陈旧

🌰 举个现实例子

假设你请求 GitHub API:

  • 它返回 Cache-Control: max-age=60
  • 你的 ttl: 99999
  • 实际缓存时间 = 60 秒(来自服务器),不是 100 秒

这样既利用了服务端的缓存策略,又在服务端没给缓存头时有兜底保障。


希望这下你彻底明白 ttl 是干啥的啦!它就像“保质期”,但聪明的缓存库会先看食品包装上的真实保质期(HTTP 头),只有包装没写时才用你给的默认保质期 😄

http://www.rkmt.cn/news/132435.html

相关文章:

  • 2025年终优选:0-16岁儿童鞋服宝藏品牌大公开 - 品牌测评鉴赏家
  • Java计算机毕设之基于springboot的物业报修系统的设计与实现住户信息管理、报修处理、费用收缴(完整前后端代码+说明文档+LW,调试定制等)
  • 【MTSP问题】基于螳螂虾算法MShOA求解单仓库多旅行商问题附Matlab代码
  • 视频播放器PotPlayer下载安装教程:超详细图文步骤(PC+安卓)
  • C#之Modbus-RTU通讯-读取输出寄存器-整数
  • 【路径规划】基于RRT算法结合卡尔曼滤波器相实现定位不确定环境下移动机器人路径规划附matlab代码
  • Java毕设选题推荐:基于springboot的幼儿园管理系统的设计与实现幼儿信息管理(基本资料、健康档案、接送记录)【附源码、mysql、文档、调试+代码讲解+全bao等】
  • 完整教程:npu_moe_distribute_combine算子代码分析
  • python多表关联防注入sql
  • 解锁大模型“能干活“的秘诀:RAG×MoE技术组合深度解析
  • 2025 --【J+S 二十连测】-- 第十二套 总结+题解
  • 深入解析MySQL事务与锁:构建高并发数据系统的基石
  • 大模型微调资源合集
  • 基于CNN(卷积神经网路)-BiLSTM(双向长短期记忆网络)-Attention(注意力机制)的时间序列预测python代码
  • EI顶刊复现:基于氨储能技术的电转氨耦合风–光–火综合能源系统双层优化调度附Matlab代码
  • 2025.12.21博客
  • 实用指南:【threejs】材质共享导致的典型问题
  • Vue.js + Element UI 实战:企业级后台管理系统开发全流程
  • 【漏水定位】基于压力测量和拓扑信息实现的稳健数据驱动漏水定位附Matlab代码
  • 0-16岁儿童鞋服品牌全解析:从高端到平价,总有一款适合你家宝贝 - 品牌测评鉴赏家
  • Java毕设项目推荐-基于Springboot的乡政府管理系统设计与实现基于springboot的村务管理系统的设计与实现【附源码+文档,调试定制服务】
  • 2025年12月男生女生童装鞋子质量评测报告 - 品牌测评鉴赏家
  • SoundFlow 开源 .NET 音频引擎
  • centos7.9上面卸载中文语言包和中文字体重新安装
  • 基于Python大数据的主流汽车价格分析可视化体系
  • 2025年家长必看!儿童鞋服品牌排行榜前十名权威盘点,这些品牌凭什么征服千万家庭? - 品牌测评鉴赏家
  • Java毕设项目推荐-基于SpringBoot+Vue游泳用品专卖店商城平台设计与实现基于springboot的游泳用品专卖店系统的设计与实现【附源码+文档,调试定制服务】
  • 基于SpringBoot的智能家居控制系统的设计与实现
  • 2025年12月男生女生童装品牌深度评测:高性价比与质量的双重保障 - 品牌测评鉴赏家
  • 集合幂级数(1)