首页 > 解决方案 > Kafka消费者onmessage - api调用对每条消息进行多次调用?

问题描述

考虑以下:

      const cached = this.cache.get(somekey);
      // console.log(!cached);
      if (!cached) {
        console.log(cached);
        return requestRetry({
          url: fullUri,
          json: true,
          maxAttempts: 3,   // (default) try 5 times
          retryDelay: 2000,  // (default) wait for 5s before trying again
          retryStrategy: requestRetry.RetryStrategies.HTTPOrNetworkError,
          fullResponse: true
        }).then((result) => {
           //do something with the result and return result
            this.cache.set(somekey, data);
            return result;
        }
     } else {
         //return cached result
     }

上面的代码在 kafka 流消费者的 onmessage 方法中被调用。我面临的问题是,如果结果不是并且缓存未定义,它会为每个传入的 kafka 消息多次调用 url。

怎样才能做到只对第一个消息进行一次调用,它设置缓存,然后在下一条消息上它进入 else 部分并从缓存中检索数据。

标签: javascriptnode.jspromisekafka-consumer-api

解决方案


只需将requestRetry结果承诺放入缓存中。
当它被解析时,缓存将更新为确切的结果。


推荐阅读