rabbitmq 学习笔记 node环境

amqp 队列

安装 rabbitmq

brew install rabbitmq;

需要配置环境变量

export AMQP_HOME=/usr/local/Cellar/rabbitmq/3.8.3/sbin
export PATH="${AMQP_HOME}:${PATH}"

rabbitmq-defaults rabbitmq-plugins rabbitmq-upgrade
rabbitmq-diagnostics rabbitmq-queues rabbitmqadmin
rabbitmq-env rabbitmq-server rabbitmqctl

启动服务

rabbimq-server 

启动服务后可以localhost:15672访问、编辑配置等功能。

  • vhost 这里可以注意下这个,guest默认 “/”

停止服务

rabbitmqctl stop

安装 ampqlib

创建连接 connect 并创建通道 channel

const url = 'amqp://test:test@localhost:5672/test';
const conn = await amqp.connect(url);
const channel =  await conn.createChannel();

创建队列

const queueOptions = {
    durable: true //true 持久的队列
}
const queueName = 'test'
channel.assertQueue(queueName,queueOptions);

生产者发送消息到队列 sendToQueue


channel.sendToQueue(queueName, Buffer.from(StringMsg), {
	persistent: true, //可靠性提升
	//exclusive: true// 断开后会丢失
});

消费者接收消息

channel.prefetch(1) //在没确认之前不接受新的消息
channel.consume(queueName, function(msg){
	//msg.content.toString() == StringMsg;
	channel.ack(msg);
}, {
	noAck: false //不自动确认
})

交换机 fanout

生产者把消息发送到交换机,消费者从指定的交换机获取队列消息

  • 生产者
const exchangeName = 'exone'
//生产者
channel.assertExchange(exchangeName, 'fanout', {
        durable: false
});
channel.publish(exchangeName,'', Buffer.from('publishMsg'));

  • 消费者
channel.assertExchange(exchange, 'fanout', {
    durable: false
});

await channel.assertQueue(queueName, queueOptions);
channel.bindQueue(queueName, exchangeName, '');
channel.consume(queueName, function(msg){
	channel.ack(msg)
},{
   noAck: false
})

交换机 direct

  • 生产者
const routerName = 'router'

channel.assertExchange(exchange, 'direct', {
    durable: false
});
for(let i =0; i<100; i++){
   let routerName = Math.random()>.5 ? 'blue' : 'green';
   const data =  await ch.publish(exchangeName, routerName, Buffer.from('publish message' + s +'--'+ i));
}
  • 消费者
channel.assertQueue(queueName, {durable: false});
channel.bindQueue(queueName, exchangeName, 'blue'); //只接收 router = blue的消息 如果想绑定多个 复制一行更改 routername就行
channel.consume(q.queue, function(msg){
   console.log(msg.content.toString());
   setTimeout(function(){
       channel.ack(msg);
   }, 40);
},{
   noAck: false
})

交换机 topic

通配筛选 routeName

  • abc.# 匹配 abc.a, abc.a.b, abc.aaa
  • abc.* 匹配 abc.a abc.b abc.aaa 但不匹配 abc.a.b;

同样 匹配符也可以放在任意位置

你可能感兴趣的:(node,js)