简体   繁体   English

我可以使用Cloudflare Workers批量处理请求吗?

[英]Can I use Cloudflare Workers to batch requests?

I would like to log requests made to my site which travel through Cloudflare. 我想记录通过Cloudflare传播到我的网站的请求。 I think I can use Cloudflare Workers to do this, but I don't want to DoS my logging service by making a request to it with every request made to my site. 我想我可以使用Cloudflare Workers来做到这一点,但是我不想通过对我的站点进行的每个请求都向它发出请求来对日志服务进行DoS。 Can I have the Worker bundle the logging reports up and only make a request to me with every 10 or 100? 我可以让Worker捆绑日志记录报告,而每10或100只向我发出一次请求吗?

To answer my own question, yes you can do this! 要回答我自己的问题,是的,您可以这样做! You have to use event.waitUntil to add a task which will run after the original request has been responded to. 您必须使用event.waitUntil添加任务,该任务将在原始请求得到响应后运行。 The one bug with this is if the Worker script gets evicted from memory, we will lose our batchedRequests , but that doesn't seem to happen very often. 这样做的一个错误是,如果从内存中清除了Worker脚本,我们将丢失batchedRequests ,但是这种情况似乎很少发生。

addEventListener('fetch', event => {
  event.respondWith(fetchAndLog(event))
})

let batchedRequests = []

function sendRequests(){
  let promises = []
  for (var i=batchedRequests.length; i--;){
    promises.push(fetch(...batchedRequests[i]))
  }

  batchedRequests = []

  return Promise.all(promises)
}
/**
 * Fetch and log a given request object, uploading a logging request only when five are stored
 * @param {Request} request
 */
async function fetchAndLog(event) {
  batchedRequests.push(["https://hookb.in/Kb88Ybq8", {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      timestamp: +new Date
    })
  }])

  if (batchedRequests.length > 4){
    event.waitUntil(sendRequests())
  }

  return fetch(event.request)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM