TypeScript 中的缓存:Redis 及其他 Node.js 解决方案

面向初学者的在线Python训练器

轻松学习Python,无需理论负担。在浏览器中直接解决带自动检查的实践任务,无需安装任何东西。

开始课程

TypeScript 中的缓存:Redis 及其他 Node.js 工具



缓存是优化 Web 应用程序性能的关键机制之一。在基于 Node.js 的 TypeScript 项目中,缓存可以减少 API 响应时间、降低数据库负载并减少外部调用的成本。在本文中,我们将介绍流行的缓存库、它们的配置以及实际示例。



为什么需要缓存?

没有缓存,每个服务器请求都可能导致重复的数据处理:从数据库读取、复杂计算或调用外部 API。缓存保存第一次调用的结果,并在后续请求中毫秒级返回。主要场景:

  • 缓存外部服务的响应(天气、汇率);
  • 存储频繁请求的数据(参考手册、配置);
  • 减少页面渲染时间;
  • 限制对数据库的请求次数。


TypeScript 中流行的缓存库



1. Redis(通过 ioredis)

Redis 是一个作为服务器运行的内存数据存储。对于 TypeScript,最好的客户端是 ioredis,它完全支持类型。安装:

npm install ioredisnpm install -D @types/ioredis


带有 TTL(生存时间)的基本缓存示例:

import Redis from 'ioredis';

const redis = new Redis({ host: 'localhost', port: 6379,});

// 将数据保存 60 秒await redis.set('user:123', JSON.stringify({ name: '安娜' }), 'EX', 60);

// 获取数据const cached = await redis.get('user:123');if (cached) { const user = JSON.parse(cached); console.log(user.name); // 安娜}


优点:分布式存储、自动键删除、支持复杂结构(列表、哈希)。缺点:需要运行 Redis 服务器,网络调用有延迟。



2. node-cache(内存中)

node-cache 是一个用于进程内缓存的简单库。不需要外部依赖。安装:

npm install node-cachenpm install -D @types/node-cache


示例:

import NodeCache from 'node-cache';

const myCache = new NodeCache({ stdTTL: 120 }); // 默认 TTL 120 秒

// 保存myCache.set('config', { theme: 'dark', lang: 'ru' });

// 获取const config = myCache.get('config');if (config) { console.log(config.theme); // dark}

// 删除myCache.del('config');


适用于不需要服务器间同步的小型应用程序。



3. memory-cache

另一个具有极简 API 的内存库。特点是简单且无依赖:

npm install memory-cache


示例:

import cache from 'memory-cache';

cache.put('weather', { temp: 22, condition: 'sunny' }, 300_000); // 5 分钟

const weather = cache.get('weather');if (weather) { console.log(`温度:${weather.temp}°C`);}

// 检查键是否存在if (cache.keys().includes('weather')) { // ...}


TypeScript 的缓存策略

策略的选择取决于数据的性质:

  • Write-through — 数据同时写入缓存和数据库。保证一致性,但增加写入时间。
  • Write-behind — 立即写入缓存,异步写入数据库。速度快,但故障时可能丢失数据。
  • Cache-aside — 应用程序自行检查缓存,未命中时从数据库读取并填充缓存。最流行的模式。


使用 ioredis 在 TypeScript 中实现 Cache-aside:

async function getUserById(id: number) {    const cacheKey = `user:${id}`;    const cached = await redis.get(cacheKey);

if

推荐