node.js - 设计模式 : Combining http requests with pluggable Redis caching mechanism

标签 node.js caching redis request

对于 API 工作,我倾向于通过围绕 Redis get/set 函数包装 http 请求来缓存第 3 方 API 响应,例如:

import http from 'request-promise-native';
import redis from 'redis';
import bluebird from 'bluebird';

bluebird.promisifyAll(redis.RedisClient.prototype);
bluebird.promisifyAll(redis.Multi.prototype);

const redisClient = redis.createClient();

const getData = async id => {
  const cacheKey = `some-key-${id}`;
  const cached = await redisClient.getAsync(cacheKey);

  if (cached) {
    return JSON.parse(cached);
  }

  const response = await http({
    method: 'GET',
    url: `https://example.com/${id}`,
    json: true,
  });

 redisClient.set(cacheKey, JSON.stringify(response), 'EX', 3600);
 return response;
}

这对于少数 API 调用很有效,但是当您有一个包含数十或数百次调用的复杂 API 时,这种方法更难维护和切换。

如果可以将其插入到 http 请求库中(在本例中为 request-promise-native),那就太理想了。

你能推荐一个更好的解决方案吗?

最佳答案

您提到的设计模式是 Decorator 函数,您还可以通过使用自定义函数包装您的 api 调用来实现它,该函数每次在访问 API 之前调用 redis。

但它绝对不应该成为 request-promise-native 的一部分,它过于宽容和固执己见。

在构建高负载/高并发应用时你应该考虑 不在热路径上执行大量 CPU 消耗任务/长时间阻塞任务/分配(创建大量新对象)

Redis 的性能受限于你机器的 cpu(1-code) & 内存 & 网络,一个简单的 vm (2 核,4gb,1gbit 网络) 可以同时处理几十 K。

在 redis 发生某些事情之前,您的 nodejs 应用程序将耗尽 cpu/内存。

关于node.js - 设计模式 : Combining http requests with pluggable Redis caching mechanism,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53293312/

相关文章:

javascript - promise 链中的返回值没有被调用

javascript - 我如何调用一个函数,其名称是通过组合node.js中的一些变量动态创建的?

javascript - 评估 javascript 的 Fetch 请求

php - 在 laravel 中全局缓存表值

lua - 返回平均值的 Redis 脚本

node.js - 在 Node 中使用redis获取哈希键的所有字段和值

caching - 当先前死掉的redis-master再次在线时如何禁用sentinel auto-slaveof

node.js - 为什么我不能使用 "ng new"语法创建新项目

c# - ASP.NET Core 2.1 - 实现 MemoryCache 时出错

java - Android 应用程序正在缓存 JSON