redis实现简单的消息队列

入队:

async create(data, priority = 'medium') {
  await app.redis.lpush(priority, JSON.stringify(data));
}

出队:

async process() {
  let priority = ['high', 'medium', 'normal'];
  let len = [
      await app.redis.get('c2').llen(priority[0]),
      await app.redis.get('c2').llen(priority[1]),
      await app.redis.get('c2').llen(priority[2])
  ];
  let queue = [];
  for (let i = 0; i < len.length; i++) {
      if (len[i]) {
          for (let h = 0; h < len[i]; h++) {
              let dataStr = await app.redis.get('c2').brpoplpush(priority[i], 'completed', 100);
              let data = JSON.parse(dataStr);
              queue.push(data);
          }
      }
  }
  return queue;
}

 

posted @ 2017-12-11 16:48  yudis  阅读(249)  评论(0编辑  收藏  举报