我的任务是将所有要使用的请求添加到Redis队列中,并从队列中逐一处理请求。为此,使用了node.js库 redis-smq 。能够将消息添加到队列中,但不能使用队列中的消息。我的redis服务器正在本地主机上的6379端口上运行
这是我的project1 index.js代码:
const express=require('express');
const app=express();
const bodyParser=require('body-parser');
const router=express.Router();
const { Message, Producer } = require('redis-smq');
const host = "localhost";
const config = {
namespace: 'test-queue',
redis: {
host: '127.0.0.1',
port: 6379,
connect_timeout: 3600000,
},
log: {
enabled: 0,
options: {
level: 'trace',
},
},
monitor: {
enabled: true,
host: '127.0.0.1',
port: 3000,
},
};
app.listen(5000, ()=> {
console.log('Server is listening at port 5000');
})
app.use((req,res,next)=>{
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With,
Content-Type, Accept");
next();
})
app.post('/queue/test', (req,res,next) => {
try {
const message = new Message();
message
.setBody({hello: 'world'})
.setTTL(3600000)
.setScheduledDelay(10);
const producer = new Producer('test_queue', config);
producer.produceMessage(message, (err) => {
if(err) {
console.log('Error while producing the message:', err);
res.status(err.status || 501).send('Error while producing the message:',err);
}
else {
console.log('Successfully produced the message');
res.status(200).send('Successfully produced the message');
}
});
}
catch(err) {
console.log('Error while connecting to redis:', err);
res.status(err.status || 501).send('Error while connecting to
redis:',err);
}
});
module.exports= app;
但是无法理解如何订阅此队列以使用node.js中的消息。根据文档,我的使用者类如下在project2中:
// filename:test-queue-consumer-launch.js
const {Consumer} = require('redis-smq');
const config = require('./redisConfig.js');
// const Consumer = redisSMQ.Consumer;
class TestQueueConsumer extends Consumer {
/**
*
* @param message
* @param cb
*/
consume(message, cb) {
console.log('Got a message to consume:', message);
//
// throw new Error('TEST!');
//
// cb(new Error('TEST!'));
//
// const timeout = parseInt(Math.random() * 100);
// setTimeout(() => {
// cb();
// }, timeout);
cb();
}
}
TestQueueConsumer.queueName = 'test_queue';
let options={
messageConsumeTimeout: 300000,
messageTTL: 500000000,
messageRetryThreshold: 3,
messageRetryDelay: 0
}
const consumer = new TestQueueConsumer(config,options);
consumer.run();
运行命令节点./test-queue-consumer-launch.js时出现以下错误:
consumer.js
[Polymer-ide] Unable to resolve superclass EventEmitter [Unknown superclass]
test-queue-consumer-launch.js
[Polymer-ide] Unable to resolve superclass Consumer [Unknown superclass]