目前的项目是一个App应用,后端API采用egg.js框架。 现在有这样一个需求
业务场景:
- API服务发送消息到阿里云消息服务 (MNS)
- 需要一个服务,获取阿里云消息服务(MNS)队列的消息,然后进行相关的业务处理
- 需要多个服务处理不同的业务 (比如发送短信,帖子新回复的提醒)
考虑用egg.js框架的扩展定时任务+阿里云消息服务(MNS)长轮询
代码示例: https://github.com/jerryhu/egg-mns-long-polling-experiment
task部分的代码如下:
'use strict';
module.exports = {
schedule: {
type: 'mns',
},
async task(ctx, message) {
console.log(`task1: ${message}`);
const condition = true;
while (condition) {
try {
// 获取消息
const resp = await ctx.app.alicloudMns.receiveMessage('test-post-reminder-queue', 25);
const data = Buffer.from(resp.body.MessageBody, 'base64').toString('utf8');
console.log(`data: ${data}`);
// TODO: 新评论提醒
// 删除消息
await ctx.app.alicloudMns.deleteMessage('test-post-reminder-queue', resp.body.ReceiptHandle);
} catch (err) {
if (err.name === 'MNSMessageNotExistError') {
console.log(`没有消息: ${new Date()}`);
continue;
}
console.error(`获取消息出错 ${err.stack}`);
break;
}
}
},
};
问题:
- 扩展定时任务中长时间执行任务是否可行?
- 有没有更优的解决方案(nodejs后端服务应用+阿里云MNS长轮询)?