// Our "Hello world" won't be too complex // let's send a message, receive it and print it on the screen // send.js - Producer sends messages to the "hello" queue. var amqp = require('amqplib/callback_api'); // connect to RabbitMQ server amqp.connect('amqp://localhost', function(err, conn) { // create a channel, which is where most of the API for getting things done resides conn.createChannel(function(err, ch) { // declare a queue for us to send to var q = 'hello'; var msg = 'Hello World!'; // then we can publish a message to the queue ch.assertQueue(q, {durable: false}); ch.sendToQueue(q, new Buffer(msg)); console.log(" [x] Sent %s", msg); }); // Lastly, we close the connection and exit; setTimeout(function() { conn.close(); process.exit(0) }, 500); });
}; rabbit.publish(q + '_gateway', message.Payload.Name, new Buffer(JSON.stringify(payload))); callback(); // we are done with this message - pull a new one // calling the callback will also delete the message from the queue }); } amqplib.connect(mq, function(err, conn) { if (err != null) { bail(err); } conn.createChannel(on_open); function on_open(err, ch) { if (err != null) bail(err); ch.assertExchange(q + '_gateway', 'fanout', { durable: true, auto_delete: false }); ch.assertExchange(q + '_distributor', 'topic', { durable: true, auto_delete: false }); ch.bindExchange(q + '_distributor', q + '_gateway'); ch.assertQueue(q, { exclusive: false, durable: true, autoDelete: false }, function(err, queue) { ch.bindQueue(q, q + '_gateway', '#');} ); pullSQS(ch); } });
#!/usr/bin/env node var amqp = require('amqplib/callback_api'); amqp.connect('amqp://localhost', function(err, conn) { conn.createChannel(function(err, ch) { var ex = 'logs-tungns'; ch.assertExchange(ex, 'fanout', { durable: false }); ch.assertQueue('', { exclusive: true }, function(err, q) { console.log(" [*] Waiting for messages in %s. To exit press CTRL+C", q.queue); ch.bindQueue(q.queue, ex, ''); ch.consume(q.queue, function(msg) { console.log(" [x] %s", msg.content.toString()); }, { noAck: true }); }); }); });
var amqp = require('amqplib/callback_api'); amqp.connect('amqp://localhost/test', function (err, conn) { conn.createChannel(function (err, ch) { var q = 'hello'; ch.assertQueue(q, { durable: true }); console.log(" [*] Waiting for message in %s. To exit press CTRL+C", q); ch.consume(q, function (msg) { console.log(" [x] Received %s", msg.content.toString()); }, { noAck: true }); }); });
#!/usr/bin/env node var amqp = require('amqplib/callback_api'); var mq = require('./rabbitcf.js'); amqp.connect('amqp://' + mq.user + ':' + mq.pass + '@' + mq.host, function(err, conn) { conn.createChannel(function(err, ch) { var q = 'task_queue'; ch.assertQueue(q, {durable: true}); ch.prefetch(1); console.log(" [*] Waiting for messages in %s. To exit press CTRL+C", q); ch.consume(q, function(msg) { var secs = msg.content.toString().split('.').length - 1; console.log(" [x] Received %s", msg.content.toString()); setTimeout(function() { console.log(" [x] Done"); ch.ack(msg); }, secs * 1000); }, {noAck: false}); }); });
#!/usr/bin/env node const R = require('ramda'), Amqp = require('amqplib/callback_api'); Amqp.connect('amqp://localhost', (err, conn) => { if (err) console.error('worker-ack_queue_ERR'); else { conn.createChannel((err, ch) => { const tq = 'worker_queue'; console.log(" [*] Waiting for messages in worker-ack.js from %s. To exit press CTRL+C", tq); ch.assertQueue(tq, {durable: R.T()}); ch.prefetch(1); ch.consume(tq, (msg) => { let secs = msg.content.toString().split('.').length - 1, millisec = 1500; console.log(" [x] Received %s %s in worker-ack.js", msg.content.toString(), secs.toString()); setTimeout(() => { console.log(" [x] Done by worker-ack.js"); ch.ack(msg); }, R.multiply(secs, millisec)); }, {noAck: false}); }); } });
#!/usr/bin/env node const Amqp = require('amqplib/callback_api') var args = process.argv.slice(2) if (args.length === 0) { console.log('Usage: receive_logs_topic.js <facility>.<severity>') process.exit(1) } Amqp.connect('amqp://localhost', (err, conn) => { conn.createChannel((err, ch) => { var ex = 'topic_logs' ch.assertExchange(ex, 'topic', { durable: false }) ch.assertQueue('', { exclusive: true }, (err, q) => { console.log('[*] Waiting for logs, To exit press CTRL+C') args.forEach(key => { ch.bindQueue(q.queue, ex, key) }) ch.consume(q.queue, msg => { console.log('[x] %s" "%s"', msg.fields.routingKey, msg.content.toString()) }, { noAck: true }) }) }) })
var amqp = require('amqplib/callback_api'); amqp.connect('amqp://localhost', function (err, conn) { conn.createChannel(function (err, ch) { var queueName = process.argv[2]; ch.assertQueue(queueName, { durable: true }); ch.prefetch(1); console.log(" [*] Waiting for messages in %s", queueName); ch.consume(queueName, function (message) { var seconds = (message.content.toString().split('.').length - 1) * 5; console.log(" [x] Received %s", message.content.toString()); setTimeout(function () { console.log(" [x] Done"); ch.ack(message); }, seconds * 1000); }); }); });
var amqp = require('amqplib/callback_api'); var ioc = require('../ioc.js'); var elastic = ioc.create('components/elasticfeature'); amqp.connect('amqp://localhost', function(err, conn) { conn.createChannel(function(err, ch) { const ex = 'topic_logs'; const key = 'error' ch.assertExchange(ex, 'topic', {durable: true}); ch.assertQueue('', {exclusive: true}, function(err, q) { console.log(' [*] Waiting for logs. To exit press CTRL+C'); ch.bindQueue(q.queue, ex, key); ch.consume(q.queue, function(msg) { elastic['addError'](msg.content.toString()); ch.ack(msg); }, {noAck: false}); }); }); });
socket.on('welcome', function(msg) { var q = msg.rb; var array_notifiche = JSON.parse(msg.array_notifiche); var decipher = crypto.createDecipher(ALGORITHM, CRYPTO_PASS_RABBIT); var id = decipher.update(q, 'hex', 'utf8'); id += decipher.final('utf8'); var FIREBASE_URL = 'https://app-giulia.firebaseio.com/Users/' + id + '.json'; amqp.connect('amqp://localhost', function(err, conn) { conn.createChannel(function(err, ch) { console.log(ch); ch.assertQueue(q, { durable: false }); console.log(" [*] Waiting for messages in %s. To exit press CTRL+C", q); ch.consume(q, function(msg_text) { console.log(msg_text.content.toString()); socket.emit(q, msg_text.content.toString()); array_notifiche.push(msg_text.content.toString()); request.get({ url: FIREBASE_URL, qs: { auth: token }, json: true, headers: { "content-type": "application/json" } }, function(error, response, body) { var persona = response.body; var requestData = { "Person": { user: persona.Person.user, email: persona.Person.email, image: persona.Person.image, luoghi: persona.Person.luoghi, photos: persona.Person.photos, friends: persona.Person.friends, feed: persona.Person.feed, notifications: array_notifiche, number: persona.Person.number + 1 } }; request.put({ url: FIREBASE_URL, qs: { auth: token }, json: true, headers: { "content-type": "application/json" }, body: requestData }, function(error, response, body) { if (!error && response.statusCode == 200) { console.log('notifica messa'); } else { console.log('problema inserimento notifica'); } }) }); }, { noAck: true }); setTimeout(function() { conn.close(); console.log("[*] Exit to %s", q); }, 500); }); }); });
amqp.connect(cloudamqpConnectionString, (error, connection) => { connection.createChannel((error, channel) => { const exchangeName = 'cnn-town-crier-ref'; channel.assertExchange(exchangeName, 'topic', {durable: true}); channel.assertQueue('cnn-google-newsstand-galleries-ref', {durable: true}, (error, queueName) => { const routingKeys = ['cnn.gallery']; routingKeys.forEach((routingKey) => { channel.bindQueue(queueName.queue, exchangeName, routingKey); }); channel.prefetch(1); channel.consume( queueName.queue, (message) => { debugLog(`AMQP Message: ${message.fields.routingKey}: ${message.content.toString()}`); log.debug(`AMQP Message: ${message.fields.routingKey}: ${message.content.toString()}`); debugLog(`Adding url to fg: ${JSON.parse(message.content.toString()).url} -> ${fg.urls}`); log.debug(`Adding url to fg: ${JSON.parse(message.content.toString()).url} -> ${fg.urls}`); fg.urls = JSON.parse(message.content.toString()).url; channel.ack(message); }, {noAck: false, exclusive: true} ); }); }); });
const amqp = require('amqplib/callback_api'); amqp.connect('amqp://localhost', (err, conn) => { conn.createChannel((err, ch) => { const q = 'hello'; ch.assertQueue(q, {durable: false}); ch.sendToQueue(q, new Buffer('Hello nice World!!!!!!!')); console.log(" [x] Sent 'Hello World!'"); }); setTimeout(() => { conn.close(); process.exit(0); }, 500); });
var amqp = require('amqplib/callback_api'); amqp.connect('amqp://localhost', function(err, conn) { conn.createChannel(function(err, ch) { ch.assertQueue("stream", {durable: false}) ch.assertQueue("stream_res", {durable: false}) //ch.sendToQueue("stream", new Buffer('Hello World!')) ch.prefetch(1); let i = 0; setInterval(() => { i += 1; let buff = new Buffer(4) buff.writeInt32BE(i) ch.sendToQueue("stream", buff) }, 0) }) });
AmqpConsumer.prototype.connect = function() { log.debug('Attempting to connect to AMQP (%s)', this.connectUrl); amqp.connect(this.connectUrl, this.socketOptions, this.onConnect.bind(this)); };
#!/usr/bin/env node const Amqp = require('amqplib/callback_api') function sendingToQueue(err, ch) { var q = 'task_queue' var msg = process.argv.slice(2).join(' ') || 'Hi Toshi!' ch.assertQueue(q, { durable: true }) ch.sendToQueue(q, new Buffer(msg), { persistent: true }) console.log(' [x] Sent %s', msg) } Amqp.connect('amqp://localhost', function (err, conn) { conn.createChannel(sendingToQueue) setTimeout(function () { conn.close() process.exit(0) }, 500) })
ch.assertExchange(ex, 'direct', exopts); ch.assertQueue('', {exclusive: true}, function(err, ok) { if (err !== null) return bail(err, conn); var queue = ok.queue, i = 0; function sub(err) { if (err !== null) return bail(err, conn); else if (i < severities.length) { ch.bindQueue(queue, ex, severities[i], {}, sub); i++; } } ch.consume(queue, logMessage, {noAck: true}, function(err) { if (err !== null) return bail(err, conn); console.log(' [*] Waiting for logs. To exit press CTRL+C.'); sub(null); }); }); }); } function logMessage(msg) { console.log(" [x] %s:'%s'", msg.fields.routingKey, msg.content.toString()); } amqp.connect(on_connect);
amqp.connect(url, function (err, conn) { conn.createChannel(function (err, ch) { var exchange = 'order_failsafe_exchange'; console.log(" [*] Waiting for messages in %s. To exit press CTRL+C", exchange); ch.assertExchange(exchange, 'x-delayed-message', {durable: true}); ch.assertQueue('', {exclusive: true}, function (err, q) { console.log(' [*] Waiting for logs. To exit press CTRL+C'); ch.bindQueue(q.queue, exchange); ch.consume(q.queue, function (msg) { try { var json = JSON.parse(msg.content.toString()); } catch (Exception) { console.log('Message is no JSON string'); return; } console.log(" [x] Received Host: '%s', Path: '%s'", json.host, json.path); var options = { host: json.host, path: json.path, method: 'GET' }; console.info('Options prepared:'); console.info(options); console.info('Do the GET call'); var reqGet = https.request(options, function (res) { console.log("statusCode: ", res.statusCode); if (res.statusCode == 200) { ch.ack(msg); console.log(" [x] Message ACK"); } res.on('data', function (d) { console.info('GET result:\n'); process.stdout.write(d); console.info('\n\nCall completed'); }); }); reqGet.end(); reqGet.on('error', function (e) { console.error(e); ch.nack(msg); return; }); console.log(" [x] Done"); }, {noAck: false}); }); }); });
gdRabbitConnector.prototype._connect = function(callback) { var url = this._getConnectionUrl(); amqp.connect(url, callback); }
var MongoClient = require('mongodb').MongoClient; var moment = require('moment'); var q = require('q'); var url = 'mongodb://localhost:27017/page_monitor'; var api = require('./api.js'); var amqp = require('amqplib/callback_api'); var when = require('when'); var _ = require('lodash'); var Q = require('q'); // Main portion of the code var connection = Q.defer(); amqp.connect('amqp://localhost', function(err, conn) { connection.resolve(conn); }); init(); function init(){ MongoClient.connect(url, function(err, db){ console.log("Connected correctly to server"); execute(db); setInterval(execute, 60000, db); }); }
var connect = (cb) => { amqp.connect(url_string, { servername: uri.hostname }, (err, conn) => { cb(err, conn); }); };
conn: function(cb) { return Amqp.connect(options.url, options.socketOptions, cb); },
if (args.length == 0) { console.log("Usage: rpc_client.js num"); process.exit(1); } amqp.connect('amqp://localhost', function(err, conn) { conn.createChannel(function(err, ch) { ch.assertQueue('', {exclusive: true}, function(err, q) { var corr = generateUuid(); var num = parseInt(args[0]); console.log(' [x] Requesting fib(%d)', num); ch.consume(q.queue, function(msg) { if (msg.properties.correlationId == corr) { console.log(' [.] Got %s', msg.content.toString()); setTimeout(function() { conn.close(); process.exit(0) }, 500); } }, {noAck: true}); ch.sendToQueue('rpc_queue', new Buffer(num.toString()), { correlationId: corr, replyTo: q.queue }); }); }); }); function generateUuid() { return Math.random().toString() + Math.random().toString() + Math.random().toString();
#!/usr/bin/env node var amqp = require('amqplib/callback_api'); var mq = require('./rabbitcf.js'); amqp.connect('amqp://' + mq.user + ':' + mq.pass + '@' + mq.host, function(err, conn) { conn.createChannel(function(err, ch) { var ex = 'logs'; var msg = process.argv.slice(2).join(' ') || 'Hello World!'; ch.assertExchange(ex, 'fanout', {durable: false}); ch.publish(ex, '', new Buffer(msg)); console.log(" [x] Sent %s", msg); }); setTimeout(function() { conn.close(); process.exit(0) }, 500); });
amqp.connect('amqp://localhost', function(err, conn) { if (err) { console.error(err); process.exit(1); } conn.on('close', function () { console.error('Connection closed'); process.exit(1); }); conn.createChannel(function(err, ch) { if (err) { console.error(err); process.exit(1); } ch.assertQueue('', {exclusive: true}, function (err, q) { if (err) { console.error(err); process.exit(1); } console.log(" [*] Waiting for messages in %s. To exit press CTRL+C", q.queue); ch.bindQueue(q.queue, 'hsl_exchange', 'vehicledata'); ch.consume(q.queue, function(msg) { msg = JSON.parse(msg.content); trams[msg.VP.veh] = msg; trams[msg.VP.veh].lastseen = Date.now(); //console.log(msg.VP.veh); }, {noAck: true}); }); }); /* RPC to return latest tram positions */ conn.createChannel(function(err, ch) { if (err) { console.error(err); process.exit(1); } var q = 'hsl_positions'; ch.assertQueue(q, {durable: false}); console.log(' [hsl_positions] Awaiting RPC requests'); ch.consume(q, function reply(msg) { ch.sendToQueue('hsl_request_channel', new Buffer(JSON.stringify({ 'channel': '*' })), {noAck: true} ); ch.sendToQueue(msg.properties.replyTo, new Buffer(JSON.stringify(trams)), { correlationId: msg.properties.correlationId, contentType: "application/json" }); ch.ack(msg); }); }); });
#!/usr/bin/env node var amqp = require('amqplib/callback_api'); amqp.connect('amqp://localhost', function(error0, connection) { if (error0) { throw error0; } connection.createChannel(function(error1, channel) { if (error1) { throw error1; } var queue = 'task_queue'; var msg = process.argv.slice(2).join(' ') || "Hello World!"; channel.assertQueue(queue, { durable: true }); channel.sendToQueue(queue, Buffer.from(msg), { persistent: true }); console.log(" [x] Sent '%s'", msg); }); setTimeout(function() { connection.close(); process.exit(0); }, 500); });
query: function(config, query, output, opts){ var amqp = require('amqplib/callback_api'); var username = config.messaging.username; var password = config.messaging.password; var hostname = config.messaging.hostname; var hostport = config.messaging.hostport; var virtualhost = config.messaging.virtualhost; var exchangename = config.messaging.exchangename; var queuename = config.messaging.queuename; var routingkey = config.messaging.routingkey; var amqp_url = 'amqp://'+username+':'+password+'@'+hostname+':'+hostport+virtualhost; amqp.connect(amqp_url, function(err, conn) { conn.createChannel(function(err, ch) { var response_queuename = queuename + 'QueryResponse'; var fs = require("fs"); // form provenance query var prov_query = ''; var uuid = guid(); prov_query += uuid+'#'; if(opts['type'] == 'FILE') { prov_query += fs.readFileSync (query).toString(); } else if(opts['type'] == 'STRING') { prov_query += query; } // setup request exchange & routingkey var request_ex = exchangename+'QueryRequest'; var response_ex = exchangename+'QueryResponse'; routingkey = routingkey +'QueryRequest'; //publish request and setup start timer var start = new Date().getMilliseconds(); ch.assertExchange(request_ex, 'direct', {durable: true}); ch.publish(request_ex, routingkey, new Buffer(prov_query)); console.log ("[PROV] Query sent sucessfully!"); // setup response exchange ch.assertExchange(response_ex, 'direct', {durable: false}); ch.assertQueue(response_queuename, {exclusive: true}, function(err, q) { console.log("[INFO] Waiting for response..."); ch.bindQueue(q.queue, response_ex, uuid); ch.consume(q.queue, function(msg) { console.log("[PROV] Query response received:\n"+msg.content.toString()); //write query response to output file var response = msg.content.toString(); fs.writeFile(output, response, function(error) { if (error) { console.error("[ERROR] File I/O Error: " + error.message); } else { console.log("[INFO] Query response successfully write to " + output); } //setup end timer and log execution time var end = new Date().getMilliseconds(); var execution_time = end - start; console.log("[INFO]Execution time: "+execution_time+"ms"); process.exit(0); }); }, {noAck: true}); }); }); setTimeout(function() { conn.close(); process.exit(0) }, 5000); }); function guid() { function s4() { return Math.floor((1 + Math.random()) * 0x10000) .toString(16) .substring(1); } return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4(); } }
rabbitMQ.connect('amqp://' + username + ":" + password + "@" + HOST, function(err, conn) { if (err != null) { console.log("[ERROR] cannot connect to rabbitMQ server, error:" + err); var fs = require('fs'); fs.unlinkSync(filename); return; } conn.createConfirmChannel(function(err, channel) { if (err != null) { console.log("[ERROR] cannot open rabbitMQ channel error:" + err); var fs = require('fs'); fs.unlinkSync(filename); return; } channel.assertQueue(dataQueue); var lineReader = require('line-reader'); var totalLines = 0; var counter = 0; var isDone = false; var trim = require("trim"); lineReader.eachLine(filename, function(line, isLast) { isDone = isLast; if (trim(line).length != 0) { totalLines++; channel.sendToQueue(dataQueue, new Buffer(line), {persistent: true}, function(err) { counter++; console.log("[OK] Send [" + counter + "][" + line + "] to server..."); if (counter == totalLines && isDone == true) { var fs = require('fs'); fs.unlinkSync(filename); console.log("END\n"); conn.close(); //process.exit(); } }); } else { conn.close(); } }); }); });
MongoClient.connect(config.get('mongodb.agenda'), function(err, db) { if (err) { logErrorAndExit('Cannot connect to MongoDB', err); } // connect to RabbitMQ amqp.connect(config.get('amqp'), function(err, conn) { if (err) { logErrorAndExit('Cannot connect to RabbitMQ', err); } conn.createChannel(function(err, ch) { if (err) { logErrorAndExit('Cannot create channel', err); } ch.assertQueue(worker.queue, {durable: true}); ch.prefetch(1); // only consume one message at a time log.info("Waiting for messages in %s. To exit press CTRL+C", worker.queue); // consume messages when they arrive ch.consume(worker.queue, function(msg) { var str = msg.content.toString(); log.info("Received %s", str); var json = JSON.parse(str); var executionId = json.executionId; var serviceId = json.serviceId; if (config.has('services.' + serviceId)) { if (json.simulate) { // simulate call - good for testing log.debug('simulate calling %s', services[serviceId].func); // update state in job state collection updateState({executionId: executionId, worker: worker, db: db}); if (worker.has('follow_queue')) { rabbit.send(worker.get('follow_queue'), str); } ch.ack(msg); } else { // call services associated wih this worker var _result = {}; async.eachSeries(worker.services, function(value, callback) { log.debug('calling %s', services[value].func); services[value].module[services[value].func](_.merge(json, _result), function(err, result) { _result._last = result; if (err) { callback(err); } else { callback(); } }); }, function(err) { // TODO: what to do in case of an error? if (err) { log.error(err); } else { log.debug('all services executed'); } // update state in job state collection updateState({executionId: executionId, worker: worker, db: db}); if (worker.has('follow_queue')) { rabbit.send(worker.get('follow_queue'), str); } // acknowledge message ch.ack(msg); }); } } else { log.warn('Cannot find service mapping for %s. Bailing out..', serviceId); ch.ack(msg); return; } }, {noAck: false}); }); }); // RabbitMQ }); // MongoDB
#!/usr/bin/env node var amqp = require('amqplib/callback_api'); amqp.connect('amqp://*****:*****@jellyfish.rmq.cloudamqp.com/ptkkvumz', function(err, conn) { conn.createChannel(function(err, ch) { var destinatario = 'Pessoa1'; ch.assertQueue(destinatario, {durable: false}); ch.sendToQueue(destinatario, new Buffer('Este é um exemplo!')); console.log(" [x] Mensagem Enviada"); }); setTimeout(function() { conn.close(); process.exit(0) }, 500); });
#!/usr/bin/env node var amqp = require('amqplib/callback_api'); var args = process.argv.slice(2); if (args.length == 0) { console.log("Usage: receive_logs_topic.js <facility>.<severity>"); process.exit(1); } amqp.connect('amqp://localhost', function(err, conn) { conn.createChannel(function(err, ch) { var ex = 'topic_logs'; ch.assertExchange(ex, 'topic', {durable: false}); ch.assertQueue('', {exclusive: true}, function(err, q) { console.log(' [*] Waiting for logs. To exit press CTRL+C'); args.forEach(function(key) { ch.bindQueue(q.queue, ex, key); }); ch.consume(q.queue, function(msg) { console.log(" [x] %s:'%s'", msg.fields.routingKey, msg.content.toString()); }, {noAck: true}); }); }); });