高效利用 Node.js 和 TypeScript 构建 LRU 缓存机制
在构建 Web 应用时,我们经常会遇到耗时操作,例如计算密集型任务或昂贵的外部 API 调用。 缓存技术能有效解决这个问题,通过存储操作结果,避免重复计算或调用。本文将演示如何使用 lru-cache
包在 Node.js 中结合 TypeScript 实现 LRU (Least Recently Used) 缓存。
首先,安装 lru-cache
包:
npm install lru-cache
接下来,创建一个最大容量为 5 的 LRU 缓存来存储用户数据:
import { LRUCache } from 'lru-cache';
interface User {
id: number;
name: string;
email: string;
}
const userCache = new LRUCache<number, User>({ max: 5 });
我们用一个模拟函数 fetchUserFromApi
模拟从外部 API 获取用户数据。该函数包含一个延迟,模拟网络请求耗时:
async function fetchUserFromApi(userId: number): Promise<User | null> {
console.log(`Fetching user data for ID: ${userId} from API...`);
await new Promise(resolve => setTimeout(resolve, 500));
const users: User[] = [
{ id: 1, name: 'Alice', email: 'alice@example.com' },
{ id: 2, name: 'Bob', email: 'bob@example.com' },
{ id: 3, name: 'Charlie', email: 'charlie@example.com' },
];
const user = users.find(user => user.id === userId);
return user || null;
}
getUser
函数利用 LRU 缓存:首先检查缓存中是否存在用户数据,若存在则直接返回;否则,从 API 获取数据并添加到缓存中。
async function getUser(userId: number): Promise<User | null> {
const cachedUser = userCache.get(userId);
if (cachedUser) {
console.log(`User data for ID: ${userId} found in cache.`);
return cachedUser;
}
const user = await fetchUserFromApi(userId);
if (user) {
userCache.set(userId, user);
}
return user;
}
主函数 main
发出多个用户数据请求,演示缓存机制和 LRU 淘汰策略:
async function main() {
// ... (identical to the original code, with minor formatting changes) ...
}
main();
首次请求用户数据时,数据来自 API。再次请求相同用户时,数据直接从缓存获取,提升速度。 LRU 缓存最大容量为 5,当请求超过容量时,最久未使用的数据会被淘汰。
使用 LRU 缓存能减少 API 负载,提升应用性能,节省资源。
本文演示了如何在 Node.js 中使用 lru-cache
包结合 TypeScript 构建 LRU 缓存机制,有效提高应用效率。 如有任何疑问,欢迎留言。
ECharts图表无法完全填充容器:原因何在,如何解决?
Travis Scott 和 Denim Tears 连帽衫背后的炒作
如何使用正则表达式验证字符串是否以特定网址开头?
React函数组件和类组件计时器:闭包问题如何解决?
ESLint 和 Tree Shaking:如何协同提高 JavaScript 项目性能?
使用OpenCV.js进行投影变换后得到空白的透明图片可能有以下几个原因:变换矩阵错误:投影变换需要一个正确的变换矩阵。如果矩阵中的参数设置不正确,可能会导致图像变换到视图之外,生成空白图像。源图像问题:如果源图像本身有问题,比如是空白或透明的,那么变换后的图像也会是空白或透明。目标图像大小设置不当:在进行投影变换时,需要指定目标图像的大小。如果目标图像大小设置得太小,可能会导致变换后的图像内容超出目标图像范围,生成空白图像。插值方法不当:OpenCV.js在进行变换时使用了不恰当的插值方法,导致图像变换