沈斌
2017-02-14 86c8cfce395beba4ad5583cbac76e5b01782a4d0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/**
 * Created by bin.shen on 03/12/2016.
 */
var amqp = require('amqplib/callback_api');
var moment = require('moment');
 
var uri = 'amqp://guest:guest@121.40.92.176';
 
module.exports.publishMessage = function(data) {
    this.pushToMQ('ex_data_dev1', {
        data: data,
        time: moment().format('YYYY-MM-DD HH:mm:ss')
    });
};
 
module.exports.pushToMQ = function(ex, data) {
    amqp.connect(uri, function(err, conn) {
        conn.createChannel(function(err, ch) {
            ch.assertExchange(ex, 'fanout', { durable: false });
            ch.publish(ex, '', new Buffer(JSON.stringify(data)));
        });
        setTimeout(function() {
            conn.close();
        }, 500);
    });
};
 
module.exports.listenToMQ = function(ex) {
    amqp.connect(uri, function(err, conn) {
        conn.createChannel(function(err, ch) {
            ch.assertExchange(ex, 'fanout', { durable: false });
            ch.assertQueue('', {exclusive: true}, function(err, q) {
                ch.bindQueue(q.queue, ex, '');
                ch.consume(q.queue, function(msg) {
                    var message = JSON.parse(msg.content);
                    global.configs[message.mac] = message;
                }, { noAck: true });
            });
        });
    });
};