javascript - 在缓存的身份验证密钥尚不存在时减少并发请求
问题描述
我目前正在构建一个位于两个服务(A 和 B)之间的微服务,并在处理数据后转发请求。此微服务用于bull
通过延迟每条消息来限制队列,并在转发数据之前向服务 B 进行身份验证。
服务 B 在 api 速率限制形式上存在一些限制,无法接收批量消息,并且每次您使用新的 TTL 检索身份验证令牌时都会轮换身份验证令牌。该令牌被存储以node-cache
供重用。
我的问题是,当前几个请求开始转发到服务 B 时,多条消息将检查node-cache
并检索新令牌,覆盖缓存的令牌,所以当第一条消息被发布时,身份验证令牌已经在服务上轮换B 和无效。
我将如何阻止或仔细检查实际检索身份验证令牌的函数?
缓存服务.js
let nodeCache = require('node-cache');
let cache = null;
exports.start = function (done) {
if (cache) return done();
cache = new nodeCache();
};
exports.instance = function () {
return cache;
};
bServiceApi.js
const cacheService = require("./cacheService");
exports.bServiceAuth = async () => {
// Check node_cache for cached auth token
// If no token is found, retrieve it
let auth_token = await cacheService.instance().get("AUTH_TOKEN");
if (auth_token == undefined) {
try {
let res = await fetch(bServiceApi, {
method: "POST",
body: params,
headers: {
Authorization: "Basic " + authKey,
},
});
const json = await res.json();
cacheService
.instance()
.set("AUTH_TOKEN", json.access_token, json.expires_in);
let auth_token = await json.access_token;
return auth_token;
} catch (err) {
console.error(err);
}
} else {
return auth_token;
}
};
消息服务.js
const { bServiceAuth } = require("./bServiceApi");
try {
bullQueue.process(async (job) => {
bServiceAuth().then((token) => {
// Do some other stuff
});
});
} catch (err) {
throw new Error(`ERROR: ${JSON.stringify(err)}`);
}
解决方案
推荐阅读
- java - 由于克隆客户端,OkHttp 连接泄漏
- javascript - vue模型对象的vue js数组属性不起作用
- angular - 使用 ngFor Angular 创建复选框列表
- python-3.x - 在 N 个父列标题 Pandas 下包含相同的列标题子集
- c# - Task.Delay 没有被取消?
- python - matplotlib arc 的 x,y 数据
- elasticsearch - Kibana,无法创建索引
- ios - 无法在 xcode 9.2 项目中安装 Cocoapods
- python - 将其他停用词附加到 nltk.corpus.stopwords.words('english') 列表或作为一组更新返回 NoneType 对象
- django - “GET /static/article/bootstrap.min.css.map HTTP/1.1”404 1700