Pri*_*tam 4 javascript amqp rabbitmq node.js php-amqplib
我正在使用RabbitMQ和Node.JS开发一个消息传递应用程序.我为此目的使用amqplib.我是Node.JS的新手,并且在理解amqplib的语法方面遇到了一些困难.例如,有一个声明队列的函数,即
channel.assertQueue([queue, [options, [function(err, ok) {...}]]]);
Run Code Online (Sandbox Code Playgroud)
我在过去的2-3天里一直在提这个,但我仍然不清楚这些 - > err和ok.如何使用这些参数?
一个例子将非常感激.
ampqlib github页面有一些关于如何使用库的示例,使用回调或promise.
我复制了他们的第一个例子,并添加了一些注释来解释发生了什么.
可能值得检查他们的教程示例,这是在官方RabbitMQ教程之后.
var amqp = require('amqplib/callback_api');
var q = 'tasks';
// connects to rabbitmq
amqp.connect('amqp://localhost', function(err, conn) {
// this function will be called when the connection is created
// `err` will contain the error object, if any errors occurred
// `conn` will contain the connection object
if (err != null) bail(err); // calls `bail` function if an error occurred when connecting
consumer(conn); // creates a consumer
publisher(conn); // creates a publisher
});
function bail(err) {
console.error(err);
process.exit(1);
}
// Publisher
function publisher(conn) {
conn.createChannel(on_open); // creates a channel and call `on_open` when done
function on_open(err, ch) {
// this function will be called when the channel is created
// `err` will contain the error object, if any errors occurred
// `ch` will contain the channel object
if (err != null) bail(err); // calls `bail` function if an error occurred when creating the channel
ch.assertQueue(q); // asserts the queue exists
ch.sendToQueue(q, new Buffer('something to do')); // sends a message to the queue
}
}
// Consumer
function consumer(conn) {
var ok = conn.createChannel(on_open); // creates a channel and call `on_open` when done
function on_open(err, ch) {
// this function will be called when the channel is created
// `err` will contain the error object, if any errors occurred
// `ch` will contain the channel object
if (err != null) bail(err); // calls `bail` function if an error occurred when creating the channel
ch.assertQueue(q); // asserts the queue exists
ch.consume(q, function(msg) { //consumes the queue
if (msg !== null) {
console.log(msg.content.toString()); // writes the received message to the console
ch.ack(msg); // acknowledge that the message was received
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5796 次 |
| 最近记录: |