首页 > 解决方案 > 在缓存的身份验证密钥尚不存在时减少并发请求

问题描述

我目前正在构建一个位于两个服务(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)}`);
  }

标签: javascriptnode.jscachingfetch

解决方案


推荐阅读