Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/37.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 节点RabbitMQ使用消息并对每条消息执行操作_Node.js_Rabbitmq_Node Amqp_Node Amqplib - Fatal编程技术网

Node.js 节点RabbitMQ使用消息并对每条消息执行操作

Node.js 节点RabbitMQ使用消息并对每条消息执行操作,node.js,rabbitmq,node-amqp,node-amqplib,Node.js,Rabbitmq,Node Amqp,Node Amqplib,我想使用来自rabbitmq服务的消息,对于收到的每条消息,我想对每条消息做一些事情(例如:将该消息放入数据库,处理该消息并通过另一个队列通过rabbitmq发送回复) 目前我的RabbitMq用户代码如下: const all = require('bluebird').all; const basename = require('path').basename; function receive() { const severities = process.argv.slice(

我想使用来自rabbitmq服务的消息,对于收到的每条消息,我想对每条消息做一些事情(例如:将该消息放入数据库,处理该消息并通过另一个队列通过rabbitmq发送回复)

目前我的RabbitMq用户代码如下:

const all = require('bluebird').all;
const basename = require('path').basename;


function receive() {
    const severities = process.argv.slice(2);
    if (severities.length < 1) {
        console.warn('Usage: %s [info] [warning] [error]',
            basename(process.argv[1]));
        process.exit(1);
    }
    let config = {
        protocol: 'amqp',
        hostname: 'localhost',
        port: 5672,
        username: 'rumesh',
        password: 'password',
        locale: 'en_US',
        frameMax: 0,
        heartbeat: 0,
        vhost: '/',
    };
    amqp.connect(config).then(function (conn) {
        process.once('SIGINT', function () {
            conn.close();
        });
        return conn.createChannel().then(function (ch) {
            let queue = 'test';
            let exchange = 'test-exchange';
            let key = 'python-key';
            let exchange_type = 'direct';

            let ok = ch.assertExchange(exchange, exchange_type, {durable: true});

            ok = ok.then(function () {
                return ch.assertQueue(queue, { durable: true});
            });

            ok = ok.then(function (qok) {
                const queue = qok.queue;
                return all(severities.map(function (sev) {
                    ch.bindQueue(queue, exchange, sev,{durable: true});
                })).then(function () {
                    return queue;
                });
            });

            ok = ok.then(function (queue) {
                return ch.consume(queue, logMessage, {noAck: true});
            });
            return ok.then(function () {
                console.log(' [*] Waiting for logs. To exit press CTRL+C.');
            });

            function logMessage(msg) {
                console.log(" [x] %s:'%s'",
                    msg.fields.routingKey,
                    msg.content.toString());
            }
        });
    }).catch(console.warn);
}


module.exports = receive;```
const all=require('bluebird')。全部;
const basename=require('path')。basename;
函数receive(){
常数严重性=进程argv切片(2);
if(严重度长度<1){
console.warn('用法:%s[info][warning][error],
basename(process.argv[1]);
过程。退出(1);
}
让配置={
协议:“amqp”,
主机名:“localhost”,
港口:5672,
用户名:“rumesh”,
密码:“password”,
地点:'en_US',
frameMax:0,
心跳:0,
vhost:“/”,
};
amqp.connect(配置)。然后(函数(连接){
process.once('SIGINT',function(){
康涅狄格州关闭();
});
返回连接createChannel().then(函数(ch){
让队列='test';
让交换='测试交换';
let key='python key';
让exchange_type='direct';
让ok=ch.assertExchange(exchange,exchange_type,{dustable:true});
确定=确定。然后(函数(){
返回ch.assertQueue(队列,{dustable:true});
});
ok=ok。然后(函数(qok){
const queue=qok.queue;
返回所有(严重性)映射(函数(sev){
bindQueue(队列,交换,sev,{dustable:true});
})).然后(函数(){
返回队列;
});
});
确定=确定。然后(函数(队列){
返回ch.consume(队列,日志消息,{noAck:true});
});
返回ok。然后(函数(){
console.log('[*]正在等待日志。要退出,请按CTRL+C.);
});
功能日志消息(msg){
console.log(“[x]%s:'%s'”,
msg.fields.routingKey,
msg.content.toString());
}
});
}).catch(控制台、警告);
}
module.exports=接收```

我建议您创建一个类似onNewMessage的处理函数,每当您在队列中收到新消息时,它都会被调用

由于可以通过AMQP发送二进制数据,因此可以采用多种方式对消息进行编码

JSON绝对是发送消息的一种方式,在Node.js中处理它非常方便

下面是一些连接到服务器,然后发送和接收消息的示例代码:

const amqp = require('amqplib');

const queue = 'test';

// Set your config here...
let config = {
    protocol: 'amqp',
    hostname: 'localhost',
    port: 5672,
    username: 'rumesh',
    password: 'password',
    locale: 'en_US',
    frameMax: 0,
    heartbeat: 0,
    vhost: '/',
};


async function start() {
    try {
        const conn = await createConnection(config);
        console.log("Connected to AMQP server.");
        let channel = await conn.createChannel();
        await channel.assertQueue(queue, { durable: true});

        startPollingForMessages(channel);
        startSendingMessages(channel);
    } catch (err) {
        console.error("start: Connection error:",err.message);
    }
}

async function createConnection(config) {
    const conn = await amqp.connect(config);

    conn.on("error", function(err) {
        console.error("Connection error:",err.message);
    });

    conn.on("close", function() {
        console.error("Connection closed:", err.message);
    });

    return conn;
}

function startSendingMessages(channel) {
    const SEND_INTERVAL = 5000;
    setInterval(() => { 
        sendMessage(channel, queue, JSON.stringify({ timestamp: new Date().toISOString(), message: " Some message" })); 
    }, SEND_INTERVAL);
}

async function sendMessage(channel, queue, messageContent) {
    console.log(`sendMessage: sending message: ${messageContent}...`);
    return channel.sendToQueue(queue, Buffer.from(messageContent))
}

function startPollingForMessages(ch) {
    ch.consume(queue, (msg) => {
        onNewMessage(msg);
        ch.ack(msg);
    });
}

function onNewMessage(msg) {
    // Do your database stuff or whatever here....
    console.log("On new message:", msg.content.toString())
}

start();

我建议您创建一个类似onNewMessage的处理函数,每当您在队列中收到新消息时,它都会被调用

由于可以通过AMQP发送二进制数据,因此可以采用多种方式对消息进行编码

JSON绝对是发送消息的一种方式,在Node.js中处理它非常方便

下面是一些连接到服务器,然后发送和接收消息的示例代码:

const amqp = require('amqplib');

const queue = 'test';

// Set your config here...
let config = {
    protocol: 'amqp',
    hostname: 'localhost',
    port: 5672,
    username: 'rumesh',
    password: 'password',
    locale: 'en_US',
    frameMax: 0,
    heartbeat: 0,
    vhost: '/',
};


async function start() {
    try {
        const conn = await createConnection(config);
        console.log("Connected to AMQP server.");
        let channel = await conn.createChannel();
        await channel.assertQueue(queue, { durable: true});

        startPollingForMessages(channel);
        startSendingMessages(channel);
    } catch (err) {
        console.error("start: Connection error:",err.message);
    }
}

async function createConnection(config) {
    const conn = await amqp.connect(config);

    conn.on("error", function(err) {
        console.error("Connection error:",err.message);
    });

    conn.on("close", function() {
        console.error("Connection closed:", err.message);
    });

    return conn;
}

function startSendingMessages(channel) {
    const SEND_INTERVAL = 5000;
    setInterval(() => { 
        sendMessage(channel, queue, JSON.stringify({ timestamp: new Date().toISOString(), message: " Some message" })); 
    }, SEND_INTERVAL);
}

async function sendMessage(channel, queue, messageContent) {
    console.log(`sendMessage: sending message: ${messageContent}...`);
    return channel.sendToQueue(queue, Buffer.from(messageContent))
}

function startPollingForMessages(ch) {
    ch.consume(queue, (msg) => {
        onNewMessage(msg);
        ch.ack(msg);
    });
}

function onNewMessage(msg) {
    // Do your database stuff or whatever here....
    console.log("On new message:", msg.content.toString())
}

start();