rabbitmq Six models
The program that sends the message is the producer
The queue represents a mailbox .
The consumer is waiting to receive messages from the queue
ConnectionFactory f = new ConnectionFactory();
f.setHost("192.168.64.140");
f.setPort(5672);// Optional ,5672 Is the default port
f.setUsername("admin");
f.setPassword("admin");
Working mode
A producer , Two consumers
rabbitmq Polling distribution messages among all consumers , Send the message evenly to all consumers
Reasonable distribution
abbitmq It will distribute more than one message at a time to consumers , This may cause some consumers to be very busy , And other consumers are free . and rabbitmq Nothing about it , It still distributes the message evenly
We can use basicQos(1)
Method , This tells rabbitmq Send consumers one message at a time , Before returning the confirmation receipt , Don't send new messages to consumers . It's about sending the message to the next idle consumer
Message persistence
When rabbitmq closed , Messages in our queue will still be lost , It doesn't lose data unless it's explicitly required
requirement rabbitmq There are two things to do without losing data : Make both queues and messages persistent (durable)
The queue is set to be persistent , You can specify parameters when defining queues durable by true
The second parameter is the persistence parameter durable
ch.queueDeclare("helloworld", true, false, false, null);
Publish and subscribe mode
We're going to do something totally different —— We're going to deliver the same message to multiple consumers . This pattern is called “ Release / subscribe ”.
Exchanges Switch
RabbitMQ The core idea of the messaging model is , The producer will never send any messages directly to the queue . actually , Usually the producer doesn't even know if the message will be delivered to any queue .
There are several types of exchanges available :direct、topic、header and fanout. We will focus on the last one ——fanout. Let's create a switch of this type , And call it " logs: ch.exchangeDeclare("logs", "fanout");
Automatically generate queue names
non-durable , Monopoly , Automatically delete
String queueName = ch.queueDeclare().getQueue();