javascript - 如何在部署到 Heroku 的 Node.js 环境中制作 Redis(Bull)队列?

标签 javascript node.js heroku redis bull

我查看了所有文档,但在寻找正确实现的示例时遇到了一些麻烦。首先,我有 Heroku Redis 附加组件,如下所示:

/image/9kcXW.png

我将 Redis 和 Bull 安装到我的 Node.js 环境中,并按如下方式设置 Redis:

const redis = require('redis');
const Queue = require('bull');
const redisClient = redis.createClient(process.env.REDIS_URL, {
    tls: {
        rejectUnauthorized: false
    }
});
const bullQueue = new Queue('queue', process.env.REDIS_URL)

我正在尝试将以下函数作为后台任务运行(这是 Heroku 对完成时间超过 0.5 秒的函数的建议):

app.post('/', async function(request, response) {
  const client = await pool.connect() //pool is just a node-postgres pool
  try {
    await client.query('BEGIN')
    let data = await function1(argumentList);
    await function2(data);
    await client.query('COMMIT')
  } catch(err) {
    await client.query('ROLLBACK')
    console.log(err)
  }
  try {
    await client.query('BEGIN')
    const setOfItems = await function3()
    var array = []
    for (item of setOfItems) {
      if (conditional) {
        array.push(item)
      }
    }
    await client.query('COMMIT')
    let job = await bullQueue.add()
    response.send(JSON.stringify(array))
  } catch(err) {
    await client.query('ROLLBACK')
    console.log(err)
  }
});

这个函数会做一些网络抓取、数据库调用和其他事情,所以就像我说的那样,它需要几秒钟才能完成。我应该如何更改我的函数以将请求添加到后台队列,然后将 JSON.stringified 'array' 返回给用户。抱歉,如果这是一个新手 Redis 问题,但我已经查看了所有文档,但我真的不确定如何继续。

最佳答案

对于初学者来说,const redis = require('redis'); 不是必需的。 Bull 在后台连接到 Redis,因此您只需在操作时为 Heroku 提供 process.env.REDIS_URL。 (如果需要,heroku config | grep REDIS 返回端点 URL)

目前,您的所有数据库代码根本没有委托(delegate)给任务队列。尝试使用

注册与队列关联的处理函数
bullQueue.process(job => {/* your database work goes here */})

参数 job 需要填充您的 worker 完成其工作所需的任何可序列化数据。您使用

填充此参数
bullQueue.add(/* job data goes here */)

高级方法可能类似于:

const Queue = require('bull');
const bullQueue = new Queue('queue', process.env.REDIS_URL)

bullQueue.process(async job => {
  console.log(job.data.argumentList);

  /* do SQL stuff */
  
  return [1, 2, 3, 4];
});

app.post('/', async (request, response) => {
  const job = await bullQueue.add({argumentList: ['some', 'data']});
  const array = await job.finished();
  response.send(JSON.stringify(array))
});

还有许多其他策略可用于获取结果。参见 returning job completions一些想法。

另见:

关于javascript - 如何在部署到 Heroku 的 Node.js 环境中制作 Redis(Bull)队列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67528225/

相关文章:

python - Heroku Node.js + Python

node.js - "Cannot POST/dialog/authorize/decision"实现 OAuthorize 示例时

javascript - 如何在 map 函数中的每个列表项上设置调用

javascript - netsuite保存的搜索多选下拉过滤器

javascript - 页面加载后的 Ajax 调用

node.js - 在没有域的 Heroku 上部署非 Web 服务器?

javascript - 我可以向cheerio 添加更多jquery 选择器吗? ( Node .js)

javascript - 计算范围内的整数

node.js - Mongoose .js : How can I update a deep embedded document by its id?

ruby-on-rails - Rails 5 Heroku 部署错误:ExecJS::ProgramError: SyntaxError: 意外的 token :名称(autoRegisterNamespace)