当前位置: 首页 > 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.jsqmd.com/news/120330/

相关文章:

  • 【NWFSP问题】基于雪橇犬算法SDO求解零等待流水车间调度问题NWFSP附Matlab代码
  • ES知识点二
  • 2025年度最值得入手的国产儿童鞋服品牌大盘点 - 品牌测评鉴赏家
  • C#之Modbus-RTU通讯-读取输出寄存器-整数
  • 【课程设计/毕业设计】基于springboot的社区团购系统的设计与实现商品管理、团长运营、订单处理、售后跟踪等功能【附源码、数据库、万字文档】
  • 休闲无聊测试AI大模型生成
  • 视频播放器PotPlayer下载安装教程:超详细图文步骤(PC+安卓)
  • 【路径规划】基于RRT算法结合卡尔曼滤波器相实现定位不确定环境下移动机器人路径规划附matlab代码
  • 【油井】基于matlab模拟隐式二维油井(含渗透率和压力随时间的变化)
  • python多表关联防注入sql
  • 2025年中国十大童装品牌盘点:从品质到风格,哪款戳中你的心? - 品牌测评鉴赏家
  • 【课程设计/毕业设计】基于springBoot物业智慧系统设计与实现基于springboot的物业报修系统的设计与实现【附源码、数据库、万字文档】
  • Java计算机毕设之基于springboot的幼儿园管理系统的设计与实现为幼儿园(含普惠园、民办园、连锁园)设计的 “家园共育 + 日常运营 + 安全监管(完整前后端代码+说明文档+LW,调试定制等)
  • Java毕设选题推荐:基于springboot的幼儿园管理系统的设计与实现幼儿信息管理(基本资料、健康档案、接送记录)【附源码、mysql、文档、调试+代码讲解+全bao等】
  • 完整教程:npu_moe_distribute_combine算子代码分析
  • 用 .NET MAUI 10 + VS Copilot 从 0 开发一个签到 App(六)登录
  • 信息学奥赛一本通 1616:A 的 B 次方
  • 微信开发者secret和appid获取方法
  • 解锁大模型“能干活“的秘诀:RAG×MoE技术组合深度解析
  • Java毕设选题推荐:基于Java+springboot招投标管理系统设计与实现基于springboot的在线招标系统的设计与实现【附源码、mysql、文档、调试+代码讲解+全bao等】
  • 2025 --【J+S 二十连测】-- 第十二套 总结+题解
  • Java计算机毕设之基于springboot的在线招标系统的设计与实现基于springboot招投标管理系统设计与实现(完整前后端代码+说明文档+LW,调试定制等)
  • 深入解析MySQL事务与锁:构建高并发数据系统的基石
  • android kotlinx.serialization用法和封装全解
  • 系统架构设计师教程资源合集
  • 什么是八股文?Java程序员春招如何提前储备?拿高薪offer?
  • 创新点解读:基于贝叶斯优化PatchTST的时间序列预测算法(附代码实现)
  • 【毕业设计】基于springboot的幼儿园管理系统的设计与实现(源码+文档+远程调试,全bao定制等)
  • AI伦理风险防控与治理体系构建 守护技术向善之路
  • AI应用架构师如何实现高效的上下文理解增强方案?