美文网首页
Rabbit MQ 与 NodeJS

Rabbit MQ 与 NodeJS

作者: lixin_karl | 来源:发表于2019-11-29 16:41 被阅读0次

    amqplib包提供了js访问Rabbit MQ 的接口

    /**
     * 生产者
      */
    let amqp = require('amqplib');
    class RabbitMQ {
        constructor() {
            this.hosts = ['amqp://192.168.94.105'];
            this.index = 0;
            this.length = this.hosts.length;
            this.open = amqp.connect({
                                hostname:'192.168.94.105',
                                port:5672,
                                 username:"karl",
                                 password:"karl"
                                     });
        }
        sendQueueMsg(queueName, msg, errCallBack) {
            let self = this;
            self.open.then(function (conn) {
                     return conn.createChannel();
                 }
            ).then(function (channel) {                                                                         return channel.assertQueue(queueName).then(function (ok) {                                                  return channel.sendToQueue(queueName, new Buffer(msg), {persistent: true});
                        }).then(function (data) {
                            if (data) {
                                errCallBack && errCallBack("success");
                                channel.close();
                            }
                        }).catch(function () { 
                            setTimeout(() => {
                                if (channel) { 
                                    channel.close();
                                }
                            }, 500)
                        });}).catch(function () { 
                            let num = self.index++;
                            if (num <= self.length - 1) {       
                                self.open = amqp.connect(self.hosts[num]);
                            } else {
                                self.index == 0;
                            }
                        });
        }
    }
    let mq = new RabbitMQ();
    var i = 1;
    setInterval(
     () => {mq.sendQueueMsg('testQueue', 'message('+(i++) +') 嘻嘻哈哈', (error) => {
              console.log(error)
      })},10000
     );
    
    
    /*
    **消费者
    */
    let amqp = require('amqplib');
    class RabbitMQ {
        constructor() {
            this.hosts = [];
            this.index = 0;
            this.length = this.hosts.length;
            this.open = amqp.connect({
                hostname:'192.168.94.105',//远程连接的话需要继续看下去
                port:5672,
                username:"karl",
                password:"karl"
            });
        }
        receiveQueueMsg(queueName, receiveCallBack, errCallBack) {
            let self = this;
            self.open.then(function (conn) { 
                return conn.createChannel();
            }).then(function (channel) { 
                return channel.assertQueue(queueName).then(function (ok) {
                            return channel.consume(queueName, function (msg) {
                                if (msg !== null) { 
                                    let data = msg.content.toString();
                                    channel.ack(msg);
                                    receiveCallBack && receiveCallBack(data);
                                }
                            }).finally(function () {
                                setTimeout(() => {
                                     if (channel) {
                                           channel.close();
                                     }
                                 }, 500)
                            });
                    })
                }).catch(function () {
                    let num = self.index++;
                    if (num <= self.length - 1) {
                         self.open = amqp.connect(self.hosts[num]);
                    } else {
                         self.index = 0;
                         self.open = amqp.connect(self.hosts[0]);
                    }   
                });
            }
    }   
    let mq = new RabbitMQ();
    setInterval(()=>{
        mq.receiveQueueMsg('testQueue',(msg) => 
        {    
               console.log(msg)
        })},500);
    
    

    安装rabbit MQ

    apt-get install rabbitmq-server //安装
    rabbitmq-server //运行rabbit mq
    rabbitmq-plugins enable rabbitmq_management //启动web可视化插件
    

    此时,通过 http://localhost:15672 查看,使用默认账户guest/guest 登录。但是远程登陆不行,继续

    vim  /etc/rabbitmq/rabbitmq.config
    添加 如下配置信息
    [
    {rabbit, [{tcp_listeners, [5672]}, {loopback_users, ["karl"]}]}
    ].
    

    重新启动rabbit mq

    然后增加新的用户可以专门用来远程登陆

    #RabbitMQ新增账号密码
    1、rabbitmqctl add_user karl karl
    #设置成管理员角色
    2、rabbitmqctl  set_user_tags  karl  administrator
    #设置权限
    3、rabbitmqctl set_permissions -p "/" karl ".*" ".*" ".*"
    #查看用户列表
    4、rabbitmqctl list_users
    

    此时,在其他电脑上输入 http://{ip}:15672 然后输入用户名密码 即可访问。

    传对象,json

    先将对象,json数据序列化,然后接收数据再反序列化。
    data = JSON.stringify(object);
    JSON.parse(data);

    与protobuf结合

    https://www.jianshu.com/p/bf227322a884

    相关文章

      网友评论

          本文标题:Rabbit MQ 与 NodeJS

          本文链接:https://www.haomeiwen.com/subject/fkugwctx.html