首页 > web前端 > js教程 > 正文

在 Nodejs 和 TypeScript 中使用 LRU 缓存

心靈之曲
发布: 2025-01-15 08:39:35
原创
1006人浏览过

高效利用 node.js 和 typescript 构建 lru 缓存机制

在构建 Web 应用时,我们经常会遇到耗时操作,例如计算密集型任务或昂贵的外部 API 调用。 缓存技术能有效解决这个问题,通过存储操作结果,避免重复计算或调用。本文将演示如何使用 lru-cache 包在 Node.js 中结合 TypeScript 实现 LRU (Least Recently Used) 缓存。

LRU 缓存设置

首先,安装 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 });
登录后复制

在 Nodejs 和 TypeScript 中使用 LRU 缓存

模拟 API 数据获取

我们用一个模拟函数 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;
}
登录后复制

使用 LRU 缓存

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;
}
登录后复制

测试 LRU 缓存

主函数 main 发出多个用户数据请求,演示缓存机制和 LRU 淘汰策略:

async function main() {
    // ... (identical to the original code, with minor formatting changes) ...
}

main();
登录后复制

LRU 缓存的工作原理及优势

首次请求用户数据时,数据来自 API。再次请求相同用户时,数据直接从缓存获取,提升速度。 LRU 缓存最大容量为 5,当请求超过容量时,最久未使用的数据会被淘汰。

使用 LRU 缓存能减少 API 负载,提升应用性能,节省资源。

总结

本文演示了如何在 Node.js 中使用 lru-cache 包结合 TypeScript 构建 LRU 缓存机制,有效提高应用效率。 如有任何疑问,欢迎留言。

以上就是在 Nodejs 和 TypeScript 中使用 LRU 缓存的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
相关标签:
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号