rabbitmq study notes node environment

amqp queue

Install rabbitmq

brew install rabbitmq;

Need to configure environment variables

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

Start service

rabbimq-server 

After starting the service, you can visit localhost:15672, edit configuration and other functions.

  • vhost Here you can pay attention to this, guest defaults to "/"

Out of service

rabbitmqctl stop

Install ampqlib

Create connection connect and create channel channel

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

Create queue

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

The producer sends a message to the queue sendToQueue


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

Consumer receives messages

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

Switch fanout

The producer sends the message to the exchange, and the consumer gets the queue message from the specified exchange

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

  • consumer
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
})

Switch direct

  • Producer
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));
}
  • consumer
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
})

Switch topic

Wildcard filter routeName

  • abc.# matches abc.a, abc.ab, abc.aaa
  • abc.* matches abc.a abc.b abc.aaa but not abc.ab;

The same match can be placed anywhere

Guess you like

Origin blog.csdn.net/uk_51/article/details/105453639